C程序陷入无限循环

C Program gets stuck in an infinite 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;
}

程序按预期运行。 唯一的问题是,如果您的每月付款较少 比利率 - 然后是您需要偿还的金额 呈指数增长,程序永不停止。

输入任何 >= 92 的数字,它似乎有效。

是22%p.a。利率正确吗?

好吧,如果我计算正确的话,如果你为 P 输入一个小于 91.67 的值,你就会陷入无限循环,因为每月还款额低于利息债务;所以你可能想为此添加一个检查。

顺便说一句,如果您将变量命名为 Interest、Base 等,则不需要注释,代码会更易于阅读。

此外,由于您正在打印付款信息直到余额为零,因此您应该在 b > 0 时循环。

我没有看到这会产生无限循环,但如果您的还款高于到期利息,这将成为一个问题,对于您的起始参数,这意味着低于 91.67。

您可能有一个错误的结束条件,所以总是打印负线。