multiple scanf in a program causing crash in c?

前端 未结 3 1778
灰色年华
灰色年华 2021-01-29 03:18
#include 

int main()
{       
    printf(\"how old are you? \");
    int age = 0;
    scanf(\"%d\", age);

    printf(\"how much does your daily habit co         


        
相关标签:
3条回答
  • 2021-01-29 03:29

    scanf("%d", daily);

    needs to become

    scanf("%d", &daily);
    

    You need to pass the address of the variable (i.e., a pointer, this is done with the &) to scanf so that the value of the variable can be changed. The same applies for your other prompt. Change it to

    scanf("%d", &age);
    

    Now you should get this when you run your program:

    % a.out
    how old are you? 30
    how much does your daily habit cost per day? 
    20
    
    this year your habit will cost you: 7300.00
    
    0 讨论(0)
  • 2021-01-29 03:32

    scanf works with references to variables

    printf("how old are you? ");
    int age = 0;
    scanf("%d", &age);
    
    printf("how much does your daily habit cost per day? \n");
    int daily = 0;
    scanf("%d", &daily); 
    
    double thisyear = daily * 365;
    
    printf("\n");
    printf("this year your habit will cost you: %.2f", thisyear);
    
    0 讨论(0)
  • 2021-01-29 03:46

    The scanf function expects a pointer.

    scanf("%d", &age);
    

    Ditto for the line where you scanf on "daily".

    0 讨论(0)
提交回复
热议问题