一个程序中的多个scanf导致c崩溃?

时间:2012-06-03 02:58:38

标签: c

#include <stdio.h>

int main()
{       
    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);

    return 0;
}

这是我的学校课程,当我写这篇文章的时候,我试图让用户1,给他们的年龄和2,他们的日常生活费用。但是当我运行这个

时,我的程序会崩溃

3 个答案:

答案 0 :(得分:3)

<击>     scanf(“%d”,每日);

需要成为

scanf("%d", &daily);

您需要将变量的地址(即指针,使用&)传递给scanf,以便可以更改变量的值。这同样适用于您的其他提示。将其更改为

scanf("%d", &age);

现在你应该在运行程序时得到这个:

% 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

答案 1 :(得分:1)

scanf函数需要一个指针。

scanf("%d", &age);

同样在“每日”扫描你的行。

答案 2 :(得分:0)

scanf适用于对变量的引用

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);