C printf 打印数组中的两个元素,而它只应打印一个元素

标签 c arrays

<分区>

我是编程新手,有点小问题......

我运行代码时的输出有点错误,输出中的第 3 行应该只有星期三。是什么导致了这个问题?

#include <stdio.h>

int main(){

    enum weekdays {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
    enum weekdays current_day;

    float highest_temperature = 0;
    float average_temperature = 0;
    float current_temperature = 0;

    char show_weekdays[7][9] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    for(current_day = Monday; current_day <= Sunday; current_day++){

        printf("Enter temperature for %s (in Celsius): ", show_weekdays[current_day]);
        scanf("%f", &current_temperature);

        average_temperature += current_temperature;

        if(current_temperature > highest_temperature){

            highest_temperature = current_temperature;

        }

    }

    average_temperature /= 7;

    printf("The average temperature was: %.2f Celsius\n", average_temperature);
    printf("The highest temperature was: %.2f Celsius\n", highest_temperature);

}

输出:

Enter temperature for Monday (in Celsius): 1
Enter temperature for Tuesday (in Celsius): 2
Enter temperature for WednesdayThursday (in Celsius): 3
Enter temperature for Thursday (in Celsius): 4
Enter temperature for Friday (in Celsius): 5
Enter temperature for Saturday (in Celsius): 6
Enter temperature for Sunday (in Celsius): 7
The average temperature was: 4.00 Celsius
The highest temperature was: 7.00 Celsius

最佳答案

字符串 "Wednesday" 需要 10 个字符,而不是 9 个。字符串以结束空字符 '\0' 结束,并包括空字符。

您拥有的声明不是非法的(这就是您没有收到编译时警告或错误消息的原因)。作为一种特殊情况,C 允许您使用字符串文字来初始化与文字的确切长度相同的数组(长度比大小小 1)。终止 '\0' 不会被存储。如果您不依赖于内容是有效字符串,那很好,但您确实如此。 (严格来说,你的程序的行为是未定义的,但这是一个我们不需要深入的微妙点。)

定义 show_weekdays 的更好方法是作为一个指针数组,每个指针指向一个字符串:

const char *const show_weekdays[] = {
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
};

(当我说“更好”时,我的意思是它更不容易出错并且更容易维护。可能需要一些额外的存储空间来保存指针,但对于这种大小的东西来说这是微不足道的。)

计算机真的擅长计数。尽可能让他们为您做。

这两个 const 确保您不会意外地尝试修改指针或它们指向的字符串。

关于C printf 打印数组中的两个元素,而它只应打印一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982892/

相关文章:

CUDA-C导入位图图像

c - 如何调试用C编写并运行在Apache2中的cgi程序?

c - 有必要用C写这些头文件吗?

php - 正则表达式数组与字符串问题

c - 有没有一种方法可以跳转到由 C 中的变量定义的行?

javascript - 有没有办法 "merge"数组内的两个对象?

java - 将字符串划分为ArrayList

java - 每当我的列大于我的行时,就会出现越界异常

python - 将图例添加到具有二进制数据的 numpy 数组的 matplotlib 图

c - 如何使用指针执行冒泡排序