简体   繁体   English

两个scanf函数,但其​​中一个读取不同的值

[英]Two scanf functions but one reads a different value

I'm struggling in letting the program read the variable total that was previously input after asking for the input for the variable month. 我正在努力让程序在要求输入变量月份后读取先前输入的变量总数。 The total is always 28257 and I don't know why. 总数总是28257,我不知道为什么。

I found out using " %c" on line 11 works, but I would like to know why "%s" doesn't. 我发现在第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;   }

you declared month as character, so you should use %c for input. 您已将month声明为字符,因此应使用%c进行输入。 %s is used for input character array. %s用于输入字符数组。 and before scanf("%c", &month); scanf(“%c”,&month)之前; , also use getchar(); ,也可以使用getchar();。 .

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM