如何使用指针或返回值将函数发送回 main?

时间:2021-04-02 13:01:17

标签: c

我正在研究一个抵押计算器项目。我已经完成了大部分工作,但我现在遇到的唯一问题是我不知道如何将我定义的函数指向 main,或者将它们返回到那里。例如:

double Ammortization(double IM, double loanAmount, double M, int n) {
    

    printf("\nMonth     Old           Monthly           Principal         Interest        New\n");
    printf("        Balance         Payment             Paid              Paid        Balance\n\n");
    double totalPaid = 0;
    for (int i = 1; i <= n; ++i) {
    double x = IM * loanAmount;
    double princPaid = M - x;
    double intPaid = M - princPaid;
    double newBal = loanAmount - M;
  
    if (newBal < 0) {
      newBal = 0;
    }
    if (i ==1) {
      printf("%3d %11.2lf%15.2lf %18.2lf%18.2lf%15.2lf\n", i, loanAmount, M, princPaid, intPaid, newBal);
    } else if (i > 1 && i <10) {
        printf("%3d %11.2lf%15.2lf %18.2lf%18.2lf%15.2lf\n", i, loanAmount, M, princPaid, intPaid, newBal);
    } else if (i >= 10 && i < 100) {
        printf("%3d %11.2lf%15.2lf %18.2lf%18.2lf%15.2lf\n", i, loanAmount, M, princPaid, intPaid, newBal);
    } else {
        printf("%3d %11.2lf%15.2lf %18.2lf%18.2lf%15.2lf\n", i, loanAmount, M, princPaid, intPaid, newBal);
    }
    printf("\n");
    loanAmount = (loanAmount + x) - M;
    totalPaid = totalPaid +intPaid + princPaid;
  } printf("\nTotal amount paid: %.2lf", totalPaid);
  
  //Not sure what to return here or how to point it back to main.
}

在 main 中,这就是我将它调用到 main 的方式,它工作正常,但我仍然需要一个返回值或一个指针:

  z = Ammortization(IM, loanAmount, M, n);

1 个答案:

答案 0 :(得分:0)

如果您不需要函数返回任何内容,请将其声明为返回 void 而不是 double。

如果您确实需要该函数返回双精度值,请添加一个包含实际值的 return 语句,以返回您想要离开函数的位置。

-- 去掉评论的注释,专注于实际答案