在c++中使用for循环时如何修复空白结果



我是Alvin,我是C++编程Languange的初学者,我有一个代码:

#include <iostream>
#include <string>
using namespace std;
int main(){
for (int i=0; i == 5; i++){
cout << i << ", ";
}
system("pause"); // i add this code to avoid program close when i try to run it
return 0;
}

当我编译时,它不会显示错误消息,即成功编译,但当我尝试运行它时,它不显示"I"值,即显示空白屏幕。有人能帮我吗。

您似乎不理解C for循环中条目的含义:

for (int i=0; i==5; i++)

平均值:

Start with i being zero (i=0)
Continue the loop, AS LONG AS i equals 5 (i==5)

换句话说,这并不意味着:

...
Continue the loop, UNTIL i equals 5

因此,您需要将i==5替换为i<=5,因为这意味着:

...
Continue the loop, AS LONG AS i is smaller or equal than 5 (i<=5)

循环测试条件中出现逻辑错误:

for (int i=0; i == 5; i++){  // the `==` will cause it to never enter the loop

应该是:

for (int i=0; i <= 5; i++){

最新更新