无法实现偶数在前奇数在后的数组排序?求修正第二版C++代码错误
C++数组奇偶排序改写代码错误分析
问题描述
我原本实现了一段可正常运行的C++代码,能将数组元素按偶数在前、奇数在后的规则排序。为简化逻辑改写了第二版代码,但运行结果不符合预期,现请求指出第二版代码的问题所在。
正确代码
#include<iostream> using namespace std; int main() { int a[5],cpy[5],ctr = 0; for (int i = 0 ; i<5 ; i++) { cout<<"Enter Value for index "<<i<<": "; cin>>a[i]; } for (int i = 0 ; i<5 ; i++) if (a[i]%2==0) { cpy[ctr]=a[i]; ctr++; } for (int i = 0 ; i<5 ; i++) if (a[i]%2!=0) { cpy[ctr]=a[i]; ctr++; } for (int i = 0 ; i<5 ; i++) cout<<cpy[i]<<" "; return 0; }
问题代码
#include<iostream> using namespace std; int main() { int a[5],cpy[5],ctr = 0; for (int i = 0 ; i<5 ; i++) { cout<<"Enter Value for index "<<i<<": "; cin>>a[i]; } for (int i = 0 ; i<5 && a[i]%2==0 ; i++,ctr++) cpy[ctr]=a[i]; for (int i = 0 ; i<5 && a[i]%2!=0 ; i++,ctr++) cpy[ctr]=a[i]; for (int i = 0 ; i<5 ; i++) cout<<cpy[i]<<" "; return 0; }
预期输出
Enter Value for index 0: 1 Enter Value for index 1: 2 Enter Value for index 2: 3 Enter Value for index 3: 4 Enter Value for index 4: 5 2 4 1 3 5
实际错误输出
Enter Value for index 0: 1 Enter Value for index 1: 2 Enter Value for index 2: 3 Enter Value for index 3: 4 Enter Value for index 4: 5 1 0 24 0 0
错误原因分析
第二版代码的核心问题出在for循环的终止条件设计错误:
- 第一个循环
for (int i = 0 ; i<5 && a[i]%2==0 ; i++,ctr++)的逻辑是:只要当前元素不是偶数,循环就直接终止,不会继续遍历数组后续元素。在测试用例中,第一个元素是奇数1,所以这个循环直接不执行,ctr保持为0。 - 第二个循环
for (int i = 0 ; i<5 && a[i]%2!=0 ; i++,ctr++)同理:当遇到第一个偶数元素(索引1的2)时,循环条件不满足,直接终止。此时只有索引0的奇数1被写入cpy数组,其余位置都是未初始化的垃圾值(输出中的0、24等),导致结果错误。
正确的逻辑应该是遍历数组所有元素,逐个判断奇偶性,而不是遇到不符合条件的元素就停止循环。你需要把奇偶判断从循环条件移到循环体内的if语句中,就像第一版代码那样。
内容的提问来源于stack exchange,提问作者spicysugar
相关产品推荐
相关产品推荐

