【问题标题】:Why is scanf() skipped?为什么 scanf() 被跳过?
【发布时间】: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", &amp;principal); 两次。我认为第二个应该是scanf("%.2f", &amp;rate);

标签: c scanf


【解决方案1】:

您对 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);
  }
}

【讨论】:

  • 在哪些情况下使用了.1f .2f?
  • @Muhammad Koziev printf() 系列函数可以使用这些格式说明符。
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
相关资源
最近更新 更多