我正在制作一个可以退还贷款的C程序。 yearInt是年利息 loanAmt是贷款总额 monthlyPay是每月付款 numberPay是每月付款的数量
由于某些原因,当我运行程序时,没有任何显示,即使我输入负数。
无论如何要解决它?
#include <stdio.h>
int main(void)
{
float yearInt = -1;
int loanAmt = -1;
float monthlyPay = -1;
int numberPay = -1;
int count = 0;
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%f", &loanAmt);
}
while (yearInt<0)
{
printf("Please enter valid yearly interest value: \n");
scanf("%f", &yearInt)
}
while (monthlyPay<0)
{
printf("Please enter valid monthly payment value: \n");
scanf("%f", &monthlyPay);
}
while (numberPay<0)
{
printf("Please enter valid number of monthly payments: \n");
scanf("%f", &numberPay);
}
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt);
else
printf("The amount of last payment is: %.2f\n", loanAmt);
}
return 0;
}
答案 0 :(得分:2)
您使用错误的格式说明符来阅读loanAmount
和numberPay
。而不是"%f"
,请使用"%d"
。
scanf("%d", &loanAmt);
和
scanf("%d", &numberPay);
另外,请务必检查scanf
的返回值,以确保它能够为所有变量分配数据。
更改循环:
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%d", &loanAmt);
}
到
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
if ( scanf("%d", &loanAmt) != 1 )
{
// Discard the rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
}
}
将所有检查放入函数并从main
调用函数仍然会更好。
int readInt(char const* prompt)
{
int val = -1;
printf("%s\n", prompt);
while ( scanf("%f", &val) != 1 || val < 0)
{
// Discard rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
// If EOF is reached, we have a problem.
if ( c == EOF )
{
exit(0);
}
printf("%s\n", prompt);
}
return val;
}
然后,使用:
loanAmount = readInt("Please enter valid loan value: ");
添加一个类似的函数来读取float
并调用它来读取float
类型的变量。
答案 1 :(得分:1)
scanf("%f", &loanAmt); // loanAmt is int
...
scanf("%f", &numberPay); //numberPay is int
在两个错误的参数中传递给%f
,因此导致UB。使用%d
说明符。
在这一个}
中缺失了 -
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
// ADD '}' here
else // ADD '{' here
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
}
在}
之前加else {
。