c - 程序在执行期间更改变量值
问题描述
我正在编写以下 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 语句中发生变化。
解决方案
这个说法
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
。
推荐阅读
- javascript - Material-UI 的 Dialog 如何允许在对话框后面进行交互?
- git - git-multimail 排除 git diff 和后续电子邮件
- matlab - 使用 Matlab 求解使用 Euler 方法的 ODE 系统
- google-cloud-platform - 从 gcp 中的 stackdriver-agent 获取 vm 正常运行时间数据?
- plot - 如何在 Gnuplot 中拟合 f(x)=a*sin^2(b*x^2 + c)
- asp.net - 在 aspx 中,字符串未被识别为有效的 DateTime
- python-3.x - 将字符串转换为列表
- hive - Hive 查询搜索分区不存在
- dataset - 如何将数据集下载到 Colab 中?遇到问题,显示“401 - 未经授权”?
- visual-studio-code - VSCode 的多种配置