C程序陷入无限循环

Mir*_*a N 1 c infinite-loop while-loop

我遇到的问题是我的代码会陷入无限循环或者会出现堆栈溢出问题,并在计算过程中开始产生负数.

我知道这个问题来自我的while循环,并且认为问题可能在于我使用的公式是线i = (r / 12)*(b - p + temp);.

但是我不确定如何解决这个问题.我的公式是试图计算12个月内每月固定利息贷款的利息,并将剩余的余额打印到屏幕上.这应该持续到平衡达到0.

#include <stdio.h>

// main function
int main()
{
    // variable declarations
    float r = 0.22;   // interest rate
    float b = 5000.0; // amount borrowed
    float p;          // payment amount
    int   m = 1;
    float temp, ti = 0;
    float i;

    // Take in data from user
    printf("Please enter the amount you wish to pay monthly: \n");
    scanf("%f", &p);
    printf("\n");

    //display interest rate, initial balance, monthly payment
    printf("r = %.2f\nb = %.1f\np = %.1f \n\n", r, b, p);

    // Month by month table showing month interest due/paid and remaining balance
    i = (r / 12) * b;
    temp = i;
    printf("%d %.2f %.2f\n", m,i,b);
    m++;

    while (i > 0) {
        i = (r / 12) * (b - p + temp);
        b = (b - p + temp);
        ti += temp;
        temp = i;
        printf("%d %.2f %.2f\n",m, i, b);
        m++;
    }
    printf("\n");
    printf("total interest paid: %.2f\n", ti);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

好吧,如果我正确地进行数学运算,看起来如果你为P输入一个小于91.67的值,你将陷入无限循环,因为每月的付款低于债务的利息; 所以你可能想要为它添加一个检查.

另外,如果您将变量命名为Interest,Base等,则不需要注释,代码也更容易阅读.

此外,由于您打印出支付信息,直到余额为零,您应该在b> 0时循环.