【问题标题】:Two scanf functions but one reads a different value两个 scanf 函数,但一个读取不同的值
【发布时间】:2018-05-16 16:17:27
【问题描述】:

在请求变量月份的输入后,我正在努力让程序读取先前输入的变量总计。总数总是28257,我不知道为什么。

我发现在第 11 行使用 " %c" 有效,但我想知道为什么 "%s" 无效。

    #include <stdio.h>  
    int main(void) { 

    int total; 
    char month;
    float sales;

    printf ("Enter total amount collected (-1 to quit): ");
    scanf("%d", &total);
    printf("Enter name of month: ");
    scanf("%s", &month);
    printf("total collections : $ %d\n", total);
    sales = (total/1.09);
    printf("sales : $ %.2f\n", sales);
    printf("county sales tax: $ %.2f\n", sales * 0.05);
    printf("state tax: $ %.2f\n", sales*0.04);
    printf("total sales tax collected: $ %.2f\n", sales *0.05 + sales *0.04);
    return 0;   }

【问题讨论】:

  • char month; scanf("%s", &amp;month); 是个问题。研究scanf() 以及"%s" 的预期。 "%s" 想要形成一个 string (一个空字符终止字符序列)。 char 太小了。
  • 您正在将“字符串”读入单个字符。

标签: c string decimal scanf


【解决方案1】:

您将 month 声明为字符,因此您应该使用 %c 进行输入。 %s 用于输入字符数组。在 scanf("%c", &month); 之前,也使用 getchar();

  • getchar();
  • scanf("%c", &month);

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多