c - 当我尝试运行我的程序时,为什么它总是崩溃?

标签 c

我是一名初学者程序员(大约一周),我的简单程序不断崩溃。我做错了什么?在我输入小时数之前它就崩溃了。请帮忙。

#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/

相关文章:

c - 在递归函数中使用 fprintf 时遇到问题

c++ - arm cortex a9 交叉编译奇怪的浮点行为

客户端/服务器 pthreads 程序未在 Valgrind 下执行。正常运行

c - 在 C 中读取/写入 .bmp 文件时出现问题

c++ - flite tts demo 运行失败

c - hashmap 的动态数组访问冲突

c 程序不工作 scanf char

c - GstBuffer 像素类型(确定 BPP)

c - 我如何在不使用 stdlib.h 的情况下执行此代码

c - 使用选择排序对数组进行排序不起作用