可选:。。。"/>
C //例3.2 计算存款利息。有1000元,想存一年。有3种方法可选:。。。
C程序设计(第四版) 谭浩强 例3.2
例3.2 计算存款利息。有1000元,想存一年。有3种方法可选:
(1)活期,年利率为r1;
(2)一年期定期,年利率为r2;
(3)存两次半年定期,年利率为r3。
请分别计算出一年后按3种方法所得到的本息和。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:
#include <stdio.h>
#include <stdlib.h>int main(){double *compoundInterest = (double*)malloc(3 * sizeof(double));double principal = 1000.0;double r1 = 0.0036;double r2 = 0.0225;double r3 = 0.0198;compoundInterest[0] = principal * (1 + r1);compoundInterest[1] = principal * (1 + r2);compoundInterest[2] = principal * (1 + r3 / 2) * (1 + r3 / 2);for(int i = 0; i < 3; i++){printf("Compound Interest %d = %.2f\n", i + 1, compoundInterest[i]);}free(compoundInterest);system("pause");return 0;
}
方法2:使用函数指针、函数的模块化设计
#include <stdio.h>
#include <stdlib.h>double fun1(double principal, double r1){return principal * (1 + r1);
}double fun2(double principal, double r2){return principal * (1 + r2);
}double fun3(double principal, double r3){return principal * (1 + r3 / 2) * (1 + r3 / 2);
}void compoundInterest(double principal, double *r, double (*fun[])(double, double)){for(int i = 0; i < 3; i++){printf("Compound Interest %d = %.2f\n", i + 1, fun[i](principal, r[i]));}
}int main(){double (*fun[3])(double, double) = {fun1, fun2, fun3};double principal = 1000.0;double *r = (double*)malloc(3 * sizeof(double));r[0] = 0.0036;r[1] = 0.0225;r[2] = 0.0198;compoundInterest(principal, r, fun);free(r);system("pause");return 0;
}
更多推荐
C //例3.2 计算存款利息。有1000元,想存一年。有3种方法可选:。。。
发布评论