C //例3.2 计算存款利息。有1000元,想存一年。有3种方法可选:。。。

编程入门 行业动态 更新时间:2024-10-23 01:33:20

C //例3.2 计算存款利息。有1000元,想存一年。有3种方法<a href=https://www.elefans.com/category/jswz/34/1770438.html style=可选:。。。"/>

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种方法可选:。。。

本文发布于:2024-03-15 07:50:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1738425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   种方法   存款利息

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!