求大佬解决这个课后题,有个小疑问
S1E9的第一题,计算房子的各个信息。我的程序跑出来和标准答案差那么几块钱,但是找不到原因,求解答!谢谢~这是我的代码:#include <stdio.h>
int main()
{
float price, area, yir, mir;//单价,面积, 年利率,月利率
float interest, loan;//利息, 贷款总额
float ave_repay, down_paymant;//月均还款,首期付款
float total_price, total_repay;//房款总额,还款总额
int ratio, time;//按揭成数, 按揭年数
printf("请输入单价(元/平方):");
scanf("%f", &price);
printf("请输入面积:");
scanf("%f", &area);
printf("请输入按揭成数:");
scanf("%d", &ratio);
printf("请输入按揭年数:");
scanf("%d", &time);
printf("请输入当前基准年利率:");
scanf("%f", &yir);
yir = yir / 100;
printf("%.2f\n", yir);
mir = yir / 12;
printf("%.2f\n", mir);
total_price = price * area;
down_paymant = (1 - 0.1 * (float)ratio) * total_price;
loan = total_price * ratio *0.1;
ave_repay = loan * (mir * pow(1 + mir, time * 12)) /
(pow((1 + mir), time *12) -1);
interest = ave_repay * time * 12 - loan;
total_repay = loan + interest;
printf("=======报告结果=======\n");
printf("房款总额:%.2f元\n", total_price);
printf("首期付款:%.2f元\n", down_paymant);
printf("贷款总额:%.2f元\n", loan);
printf("还款总额:%.2f元\n", total_repay);
printf("支付利息:%.2f元\n", interest);
printf("月均还款:%.2f元\n", ave_repay);
return 0;
}
这是小甲鱼的代码:
#include <stdio.h>
#include <math.h>
int main()
{
float price, area, yir, mir; // 单价、面积、年利率、月利率
float interest, loan; // 利息、贷款总额
float ave_repay, down_payment; // 月均还款、首期付款
float total_price, total_repay; // 房款总额、还款总额
int ratio, time; // 按揭成数、按揭年数
printf("请输入单价(元/平方):");
scanf("%f", &price);
printf("请输入面积:");
scanf("%f", &area);
printf("请输入按揭成数:");
scanf("%d", &ratio);
printf("请输入按揭年数:");
scanf("%d", &time);
printf("请输入当前基准年利率:");
scanf("%f", &yir);
mir = yir / 100 / 12; // 年利率需要除以100得到,因为用户输入是5.4(%),而不是0.054
time = time * 12;
total_price = price * area;
loan = total_price * ratio / 10; // 这里不能写成(ratio / 10),否则结果会变成0
ave_repay = loan * mir * pow((1 + mir), time) / (pow((1 + mir), time) - 1);
interest = ave_repay * time - loan;
total_repay = loan + interest;
down_payment = total_price * (1 - (float)ratio / 10); // 强制转换ratio为浮点型
printf("========== 报告结果 ==========\n");
printf("房款总额:%.2f元\n", total_price);
printf("首期付款:%.2f元\n", down_payment);
printf("贷款总额:%.2f元\n", loan);
printf("还款总额:%.2f元\n", total_repay);
printf("支付利息:%.2f元\n", interest);
printf("月均还款:%.2f元\n", ave_repay);
return 0;
}
以下是差别:
https://p.pstatp.com/origin/137bd00004a023a4f1330 使用pow函数里面参数定义为double类型的好,要不容易出现精度损失
double mir,time; // 因为pow函数里需要用这两个参数,改为double型,减小精度损失
scanf("%lf", &time); //改为%lf 不同编译器间计算的浮点数精度可能会不一样,想办法减小这个误差就行了 巴巴鲁 发表于 2020-9-11 23:06
使用pow函数里面参数定义为double类型的好,要不容易出现精度损失
谢谢!以后用pow会更加注意 leon_xinxin 发表于 2020-9-12 15:09
谢谢!以后用pow会更加注意
如果没错的话最后的结果是一样的,但还款总额和肌肤利息会有误差,pow函数原型就是double pow(double , double )
页:
[1]