gpt4 book ai didi

C程序陷入无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:14 25 4
gpt4 key购买 nike

我一直遇到的问题是,我的代码要么陷入无限循环,要么出现堆栈溢出问题,并在计算过程中开始产生负数。

我知道这个问题来 self 的 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;
}

最佳答案

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

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

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

关于C程序陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com