C语言如何正确打印二维数组元素?月份天数查询代码输出异常求解
问题原因分析
printf参数不匹配:你使用的格式化字符串"In month %d there are %d days\n"需要传入2个int类型参数,但代码中仅传入了monNum[i][j]1个参数,第二个占位符读取的是栈内存随机值,就是输出中异常数字的来源。- 遍历逻辑错误:你的二维数组每一行
monNum[i]的结构为[月份数, 当月天数],不需要嵌套两层循环遍历每个元素,直接取同一行的两个元素即可完成打印。 - 判断逻辑位置错误:你将
Choice的范围判断放在了内层循环中,会导致重复判断,且没有匹配用户输入的月份就直接打印所有行内容。
修正后代码
#include <stdio.h> int main(void) { int Choice = 0; int monNum[12][2] = { {1,31}, {2,28}, {3,31}, {4,30}, {5,31}, {6,30}, {7,31}, {8,31}, {9,30}, {10,31}, {11,30}, {12,31} }; int i; printf("Enter a number between 1 and 12 (for a month), 99 for all months. (0 to quit):"); scanf("%d", &Choice); if (Choice >= 1 && Choice <=12) { // 输入月份减1即为对应数组行下标 int index = Choice - 1; printf("In month %d there are %d days\n", monNum[index][0], monNum[index][1]); } else if (Choice == 99) { // 打印所有月份逻辑,无需内层j循环 for(i=0; i<12; i++) { printf("In month %d there are %d days\n", monNum[i][0], monNum[i][1]); } } else if (Choice == 0) { return 0; } // 可自行补充输入非法值的提示逻辑 return 0; }
补充说明
如果后续需要处理闰年2月的天数调整,只要在获取Choice之后添加闰年判断逻辑,修改monNum[1][1]的值为29即可,不需要改动其他打印逻辑。
内容的提问来源于stack exchange,提问作者AnotherStudent
相关产品推荐
相关产品推荐

