c - 函数没有将整个值返回给 main
问题描述
我试图让我的函数将 M 的值返回给 main,但它不返回完整值。例如,M = 397.73,但在 main 中调用打印时,它只返回 397.00。我尝试使用的输入是 100000、2.55、30。这就是为什么我的预期输出是 397.73。
int main(void) {
int loanAmount;
double APR;
int time;
double M;
printf("Enter in loan amount:\n");
scanf("%d", &loanAmount);
printf("Enter APR: \n");
scanf("%lf", &APR);
printf("Enter loan time (years): \n");
scanf("%d", &time);
printf("Loan amount: %7d\nAPR: %13.2f%%\nTime of loan: %d years\n", loanAmount, APR, time);
M = CalculatePayment(M, loanAmount, APR, time);
printf("%.2lf", M); //This is where my issue comes from, this only prints partial of M.
return 0;
}
int CalculatePayment(double M, int P, double c, int d) {
//M= P * r(1+r)^n/(1+r)^n-1
int n = d * 12; //number of months of loan.
double IM = (c / 100) / 12; //monthly interest rate.
M = P * ((IM * pow(1 + IM, n)) / (pow(1+IM, n) - 1)); // calculates monthly payment.
printf("%.2lf\n", M);
return M;
}
解决方案
的返回类型CalculatePayment
为int
,因此返回值被截断为整数。
改为double
用作返回类型。
推荐阅读
- css - 悬停时颜色滑动悬停应继续移动保存方向
- c++ - B树的垂直顺序遍历->错误“第924行:字符9:运行时错误:引用绑定到'int'类型的空指针(stl_vector.h)”
- node.js - twilio 视频聊天应用程序中的 React 应用程序错误 431(请求标头字段太大)
- c++ - c ++ esc / p 打印机由于某种原因无法通过 com5 端口打印
- powershell - PowerShell 上的 tshark 作业不输出捕获文件
- firebase - 无法弄清楚如何仅显示我单击的帖子的帖子详细信息
- autodesk-forge - GL_INVALID_OPERATION:缺少片段着色器输出的活动绘制缓冲区
- node.js - 为什么我在使用 `npm` 安装东西时会出错?
- javascript - 如何在特定时区创建新的日期对象?
- c# - 如何使用此函数(HttpPostRequest)填充输入框(控制台应用程序)?