【问题标题】:scanf doesn't read in int properlyscanf 未正确读取 int
【发布时间】:2020-04-11 11:03:54
【问题描述】:

我也尝试过添加 fflush(stdout);在 printf 语句之后并没有做任何事情,在 scanf 之前也没有使用 fflush(stdin)

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>


float cost(int qty)
{
    if (qty <= 20)
        return qty * 23.45;
    if (qty >= 21 && qty <= 100)
        return qty * 21.11;
    if (qty > 100)
        return qty * 18.75;
    return '0';
}

// void main() VS Only
int main()
{
    int q;

    printf("Enter quantity of books wanted: ");
    scanf("&d", &q);

    printf("\n\nThe total cost for purchasing books is: $%0.2f\n\n", cost(q));
}

【问题讨论】:

  • 您观察到哪些不正确的行为?给出准确的输入、预期行为和实际行为。
  • #include &lt;conio.h&gt;添加这个
  • 注意:return '0'; 可能不会像您认为的那样做。 ITYMreturn 0;.
  • Renatus,最大的错误是没有完全启用警告。省时间。全部启用。 scanf("&amp;d", &amp;q); 应该收到警告,例如“警告:格式 [-Wformat-extra-args] 的参数过多”/

标签: c scanf


【解决方案1】:

scanf() 函数的第一个参数错误。 对于 int,格式字符是“%d”。 你输入“&d”。

您可以调用系统(“PAUSE”)来保持终端打开并查看结果。

...
scanf("%d", &q);
...
system("PAUSE");

scanf() 示例和参考: http://www.cplusplus.com/reference/cstdio/scanf/

【讨论】:

    【解决方案2】:

    您传递了错误的整数格式说明符,请将 scanf("&amp;d", &amp;q); 更改为 scanf("%d", &amp;q);

    【讨论】:

      【解决方案3】:

      scanf("%d",&amp;q)的参数
      数据类型前应该有%
      数据类型 - d for int
      &amp;d to %d

      【讨论】:

        猜你喜欢
        • 2012-03-18
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 2015-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多