如何打印数组中元素值对应的位置?现有C语言代码运行结果异常求排查
问题原因分析
- 第一个核心逻辑错误:两个循环内的条件判断都没有加花括号包裹关联逻辑,导致
pos = x和position = y两行代码不属于if判断分支,每次循环无论条件是否成立都会执行。循环结束后遍历变量x/y的最终值为9,所以位置永远输出9。 - 第二个逻辑错误:求最大值的初始值错误赋值为
array[10],C语言数组下标从0开始,长度为10的数组合法下标范围是0~9,array[10]属于数组越界访问,读取的是数组外的未知内存值,会导致最大值计算结果错误。
修正后代码
int smallest = array[0]; int pos = 0; for (int x = 0; x < 10; x++) { if (array[x] < smallest) { smallest = array[x]; pos = x; } } printf("%d is the smallest number and its located in %d\n", smallest, pos); printf("\n"); int largest = array[0]; int position = 0; for (int y = 0; y < 10; y++) { if (array[y] > largest) { largest = array[y]; position = y; } } printf("%d is the largest number and its located in %d\n", largest, position);
可选优化建议
- 可以合并两个循环,一次遍历同时计算最大值和最小值,减少数组遍历次数,提升运行效率。
- 避免硬编码数组长度10,可以用
sizeof(array)/sizeof(array[0])动态获取数组长度,提升代码通用性。
内容的提问来源于stack exchange,提问作者Fabrizio Liani
相关产品推荐
相关产品推荐

