首页 > 解决方案 > 程序在执行期间更改变量值

问题描述

我正在编写以下 C 程序。在这个阶段,程序应该从用户那里获取输入并将其存储到变量中days

#include <stdio.h>
#define SIZE 10

int main(){
    int days = 0;
    int high_temp[SIZE] = {0};
    int low_temp[SIZE] = {0};

    printf("---=== IPC Temperature Calculator V2.0 ===---\n");

    if ((days < 3) || (days > 10)) {

        printf("Please enter the number of days, between 3 and 10, inclusive: %d");
        scanf("%d", &days);

        while ((days < 3) || (days > 10)) {
            printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: ");
            scanf("%d", &days);
            printf("\n");
        }
    }

    for(int i = 1; i < days; i++){
        printf("\nDay %d - High: ", i);
        scanf("%d", &high_temp);

        printf("\nDay %d - High: ", i);
        scanf("%d", &low_temp);
    }

}

但是,在执行过程中,该问题为 分配了一个荒谬的值days

---=== IPC Temperature Calculator V2.0 ===---
Please enter the number of days, between 3 and 10, inclusive: 87585440

请注意,它days被初始化为 0,并且该值应该在 if 语句中发生变化。

标签: cruntime-error

解决方案


这个说法

printf("Please enter the number of days, between 3 and 10, inclusive: %d");

具有未定义的行为。%d从输出的字符串中删除。

写吧

printf("Please enter the number of days, between 3 and 10, inclusive: ");

如果您想使用说明符作为提示,请编写

printf("Please enter the number of days, between 3 and 10, inclusive: %%d");

那是用的%%d


推荐阅读