如何将C++中的for循环转换为while循环?附示例代码
把C++的for循环转换为while循环的实现
当然可以啦!在C++里,for循环和while循环完全可以互相替代——for循环本质就是把初始化、条件判断、增量操作这三个步骤打包到了一起,拆开来调整顺序就能变成while循环。我来帮你把这段代码里的三个循环都转换成while版本,顺便修正原代码里的小逻辑问题~
1. 求和循环的转换
原for循环代码
int sum = 0; for (int i = 0; i < length; i++) { sum = sum + MyList[i]; } cout << "The Total is: " << sum << endl;
转换后的while循环代码
int sum = 0; int i = 0; // 把循环变量的初始化移到循环外面 while (i < length) { // 条件判断和for循环里的一致 sum = sum + MyList[i]; i++; // 增量操作放到循环体的末尾 } cout << "The Total is: " << sum << endl;
2. 找最大值循环的转换
原for循环代码(注:原代码存在逻辑小问题,cout时机不对)
int largest = MyList[0]; for (int i = 0; i < length; i++) if (MyList[i] > largest) cout << "The Largest Value is: " << largest << endl;
转换后的while循环代码(同时修正逻辑问题)
int largest = MyList[0]; int i = 0; while (i < length) { if (MyList[i] > largest) { largest = MyList[i]; // 先更新最大值,再考虑输出 } i++; } // 循环结束后输出最终的最大值,这样才合理 cout << "The Largest Value is: " << largest << endl;
3. 找最小值循环的转换
补全后的原for循环代码
int smallest = MyList[0]; for (int i = 0; i < length; i++) if (MyList[i] < smallest) smallest = MyList[i]; cout << "The Smallest Value is: " << smallest << endl;
转换后的while循环代码
int smallest = MyList[0]; int i = 0; while (i < length) { if (MyList[i] < smallest) { smallest = MyList[i]; } i++; } cout << "The Smallest Value is: " << smallest << endl;
转换的核心要点总结
- 把for循环里的循环变量初始化(比如
int i=0)移到while循环的外面; - while循环的括号里只放条件判断(比如
i < length),和for循环的条件完全一致; - 把for循环末尾的增量操作(比如
i++)放到while循环体的最后执行; - 循环体里的业务逻辑保持不变即可。
内容的提问来源于stack exchange,提问作者GadhviPonyTail
相关产品推荐
相关产品推荐

