我正在编写以下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语句中更改。
答案 0 :(得分:2)
此声明
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
的。
答案 1 :(得分:2)
您的printf()
调用包含%d
的格式说明符,但是您没有在格式后面传递整数。这是未定义的行为,正在从内存中提取一些未知值。
如果要打印days
的值,则需要在函数调用中传递它。如果不是,则删除%d
说明符。
printf("Please enter the number of days, between 3 and 10, inclusive: %d", days);
答案 2 :(得分:0)
走了,希望对您有帮助
#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]);
}
}