Simple interest refers to an interest calculation method in which the principal gets interest within a certain period of time in bank deposits, and the interest does not generate interest. The following is a simple interest calculation function implemented in C++ and its comments:
#include <iostream>
using namespace std;
// 计算单利
double simple_interest(double principal, double rate, int time) {
double interest = principal * rate * time; // 计算利息
return principal + interest; // 返回本息和
}
int main() {
double principal; // 本金
double rate; // 年利率
int time; // 存款时间(以年为单位)
// 输入本金、年利率和存款时间
cout << "请输入本金:";
cin >> principal;
cout << "请输入年利率:";
cin >> rate;
cout << "请输入存款时间(以年为单位):";
cin >> time;
// 计算本息和
double result = simple_interest(principal, rate, time);
// 输出结果
cout << "本金 " << principal << " 元,年利率 " << rate*100 << "%,存款时间 " << time << " 年,获得利息 " << result - principal << " 元,本息和 " << result << " 元。" << endl;
return 0;
}
In the above code, we first define a simple_interest
function named , which calculates simple interest. The function accepts three parameters: principal
the principal, rate
the annual interest rate, time
and the deposit time (in years). Inside the function, the interest is first calculated interest
, and then the principal and interest are added together to obtain the sum of principal and interest result
. Finally, the function returns the sum of principal and interest result
.
In the main function, we first read the principal, annual interest rate and deposit time from standard input. Then, call simple_interest
the function to calculate the sum of principal and interest, and output the result to the standard output.
After executing the above code, the program will prompt the user to input principal, annual interest rate and deposit time, and then output the calculated interest and the sum of principal and interest.
#include <iostream>
using namespace std;
double simple_interest(double principal, double rate, int time) {
double interest = principal * rate * time; // 计算利息
return principal + interest; // 返回本息和
}
int main() {
double principal = 1000; // 定义本金
double rate = 0.025; // 定义年利率
int time = 1; // 定义存款时间
double result = simple_interest(principal, rate, time); // 调用函数,计算本息和
// 输出结果
cout << "本金 " << principal << " 元,年利率 " << rate * 100 << "%,存款时间 " << time << " 年,获得利息 " << result - principal << " 元,本息和 " << result << " 元。" << endl;
return 0;
}