首页 > 解决方案 > 函数没有将整个值返回给 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;
}

标签: c

解决方案


的返回类型CalculatePaymentint,因此返回值被截断为整数。

改为double用作返回类型。


推荐阅读