Программа изменяет значение переменной во время выполнения - PullRequest
2 голосов
/ 28 марта 2020

Я пишу следующую 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.

Ответы [ 3 ]

2 голосов
/ 28 марта 2020

Ваш printf() вызов содержит спецификатор формата %d, но вы не передаете целое число после формата. Это неопределенное поведение, и оно извлекает какое-то неизвестное значение из памяти.

Если вы хотите напечатать значение days, вам нужно передать его в вызов функции. Если нет, то удалите спецификатор %d.

printf("Please enter the number of days, between 3 and 10, inclusive: %d", days);
2 голосов
/ 28 марта 2020

Это утверждение

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.

0 голосов
/ 28 марта 2020

вот вам go, надеюсь, это поможет

#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: ");
    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 = 0; i < days; i++){
    printf("\nDay %d - High: ", (i+1));
    scanf("%d", &high_temp[i]);

    printf("\nDay %d - Low: ", (i+1));
    scanf("%d", &low_temp[i]);
}

for (int i = 0; i < days; i++){

   printf("\n Day # %d", (i + 1));
   printf("\n\t High: %d", high_temp[i]);
   printf("\n\t Low: %d", low_temp[i]); 
}

}

...