gpt4 book ai didi

c++ - for循环/while循环背后的逻辑

转载 作者:行者123 更新时间:2023-12-02 10:08:45 32 4
gpt4 key购买 nike

我需要帮助来了解while循环/ for循环之间的逻辑差异,这是示例代码:

#include<iostream>
using namespace std;

int main(void)
{
cout << "A multiplication table:" << endl
<< " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl
<< "" << endl;
for(int c = 1; c < 10; c++)
{
cout << c << "| ";
for(int i = 1; i < 10; i++)
{
cout << i * c << '\t';
}
cout << endl;
}
return 0;
}

我尝试将其重写为while循环,但是结果缺少信息。
#include <iostream>
using namespace std;


int main() {
int i = 1;
int c = 1;
while (c< 10){
cout << c <<"|";
c++;
while (i< 10){
cout << i * c << '\t';
i++;


}
cout << endl;
}

cin.clear();
cin.ignore();
cin.get();

return 0;
}

有人建议将i重置为1会得到其余结果,但我很难理解为什么while循环需要重置,而for循环却不需要。

最佳答案

您必须将i = 1设置才能在两个示例中都获得预期的行为。对于for循环,这已经得到了解决,因为在for循环的 header 中有for( int i = 1 ; ...; ...)。

关于c++ - for循环/while循环背后的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516116/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com