这个程序我用DEV-C++编写的。
复利计算就是帮助用户计算存款在一定的利息下,存入一定年限后本金加上利息总共多少。下面是实现该功能的一个简单程序:
#include<stdio.h>
int main(void) {
double principal, interest_rate, total;
int years;
printf("This programme will help you caculate the interest.\n");
printf("Please input your principal: ");
scanf("%lf", &principal);
printf("Please input the interest rate: ");
scanf("%lf", &interest_rate);
printf("Please input the term of deposit: ");
scanf("%d", &years);
printf("Years Total\n");
for (int i = 1; i <= years; i++) {
principal += principal * interest_rate / 100;
printf("%d\t%.3lf\n", i, principal);
}
return 0;
}
下面是该程序运行情况:
如果用户存入年限较短,如5年、10年等,可以直接在终端窗口显示。但用户如果存入50年,在这样的窗口显示看着会非常的麻烦,并且在下一次想看自己存款本金和所得利息时需要重新运行程序,这样会耗费大量的时间和精力。如果我们能将这些数据存入一个txt文本文档中,将会节省用户不必要的操作。
改进代码如下:
#include<stdio.h>
int main(void) {
double principal, interest_rate;
int years;
char filename[100];
char mode[2];
printf("This programme will help you caculate the interest.\n");
printf("Please input your principal: ");
scanf("%lf", &principal);
printf("Please input the interest rate: ");
scanf("%lf", &interest_rate);
printf("Please input the term of deposit: ");
scanf("%d", &years);
printf("Please enter the file name to save the results(e.g. output.txt): ");
scanf("%s", filename);
printf("Please enter file mode('w' for write, 'a' for append): ");
scanf("%s", mode);
FILE* file = fopen(filename, mode);
if (file == NULL) {
perror("Error opening file");
return 1;
}
fprintf(file, "Years Total\n");
for (int i = 1; i <= years; i++) {
principal += principal * interest_rate / 100;
if (fprintf(file, "%d\t\t\t%.3lf\n", i, principal) < 0) {
printf("Error writing to file!\n");
fclose(file);
return 1;
}
}
fclose(file);
printf("Caculation complete.Results save to '%s'\n", filename);
return 0;
}
我们只需要在桌面上新建一个文本文档,如interest_caculation.txt,然后如下图所示:
我们就将50年的数据写入了interest_caculation.txt文档中。
下面,我们打开文档:
建立文档进行阅读的好处还有阅读方便,便于操作等。
那么,建立文档来储存数据这种方法,不仅可以应用于复利计算,还可以应用于其他场景。
如:某种细菌正常情况下每10分钟分裂一次,那么一个该细菌在正常生长环境中,连续分裂10天后,总共有多少细菌?
再如:给定某放射性金属衰变周期,在无外界影响下,一定质量的该金属1年后放射性剩多少?
这样,我们可以清晰地看到每周期的数据,易于分析。
如果用数组编写该程序(我觉得没有多少必要用数组编写此程序):
#include<stdio.h>
#include<math.h>
#include<stdlib.h> //包含malloc和free函数的头文件
void calculateCompoundInterest(double principal, double rate, int years, double amounts[]){
for(int year = 1; year <= years; year++){
amounts[year - 1] = principal * pow(1 + rate, year);
}
}
int main(){
double principal;
double rate;
int years;
printf("Please input the principal: ");
scanf("%lf", &principal);
printf("Please input the rate: ");
scanf("%lf", &rate);
printf("Please input the years: ");
scanf("%d", &years);
double *amounts = (double *)malloc(years * sizeof(double));
if(amounts == NULL){
printf("Error\n");
return 1;
}
calculateCompoundInterest(principal, rate, years, amounts);
printf("The result:\n");
for(int year = 1; year <= years; year++){
printf("Year: %d money: %.3lf\n", year, amounts[year - 1]);
}
free(amounts);
return 0;
}
本金为200000,年利率为0.02,存100年。
运行结果(部分截图):
文章若有不足之处,请各位大佬批评指正!