我是一名初学者程序员(大约一周),我的简单程序不断崩溃。我做错了什么?在我输入小时数之前它就崩溃了。请帮忙。
#include <stdio.h>
#include <stdlib.h>
int hours;
float wage;
float total[2];
int main()
{
printf("How many hours have you worked this week?\n");
fgets(hours, sizeof(hours), stdin);
sscanf(hours,"%d", &wage);
if (hours < 40)
wage = 8.5;
total[0] = hours * wage;
printf("You will earn %d dollars", total[0]);
if (hours >= 40)
wage = 12.75;
total[1] = hours * wage;
printf("You will earn %d dollars", total[1]);
return 0;
}
最佳答案
我认为问题出在这里:
fgets(hours, sizeof(hours), stdin);
fgets
不执行格式化输入,因此当它尝试使用整数值 hours
作为指向应读取的缓冲区。
要解决此问题,请尝试以下操作:
scanf("%d", &hours);
下一行还有一个完全不必要且格式错误的 scanf
:
sscanf(hours,"%d", &wage);
scanf 的语法是
scanf(formatting-string, destinations...);
因此,它应该看起来像这样:
scanf("%f", &wage);
您绝对应该提高编译器的警告级别;我很惊讶这个编译时没有向您发出警告,解释正在发生的事情。
printf
语句中的格式说明符也存在问题:
printf("You will earn %d dollars", total[0]);
请注意,total[0]
是 float
,而不是 int
,因此 %d
不合适。尝试使用 %f
代替。
希望这有帮助!
关于c - 当我尝试运行我的程序时,为什么它总是崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19914506/