为什么跳过 scanf()?

Why is scanf() skipped?

您能解释一下为什么只有第一个 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 的使用无效。您不能使用 .2f,因为“.”不支持修改器。请修复此代码

#include <stdbool.h>
#include <stdio.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);
  }
}