【发布时间】:2021-11-07 23:51:06
【问题描述】:
你能解释一下为什么只有第一个scanf() 有效,而其他的被跳过了吗?这发生在我在 PC 上编写但在其他计算机上有效的每个代码中。
#include <stdio.h>
#include <stdbool.h>
int main()
{
float interest, principal, rate;
int days;
while(true)
{
if(principal == -1)
{
break;
}
printf("Enter loan principal (Enter -1 to end): \n");
scanf("%.2f", &principal);
printf("Enter interest rate: \n");
scanf("%.2f", &rate);
printf("Enter term of the loan in days: \n");
scanf("%d", &days);
}
}
输出:
Enter loan principal (Enter -1 to end):
-1
Enter interest rate:
Enter term of the loan in days:
Enter loan principal (Enter -1 to end)
【问题讨论】:
-
对于初学者,您需要检查
scanf()的返回值,看看是否成功。 -
您将利率写入本金。您确定要这样做吗?
-
与
scanf无关,但是在检查-1之前没有初始化principal。 -
“被跳过”是什么意思?另外,你正在做
scanf("%.2f", &principal);两次。我认为第二个应该是scanf("%.2f", &rate);