将while循环转换为等效的for循环

Convert while loop to an equivalent for loop

本文关键字:循环 for while 转换      更新时间:2023-10-16

这是有while循环的代码,我希望帮助将这些代码转换为等价的for循环

 #include<stdio.h>
    void main()
    {
        int x = 1;
        int y;
        while(x<=10)
        {
            y=x*x;
            cout<<x<<endl<<y;
            x = x+3;
            getch()
        }

试试这个:

#include <stdio.h>
void main()
{
    int y;
    for (int x = 1; x <= 10; x += 3)
    {
        y = x * x;
        cout << x << endl << y;
        getch();
    }
}
#include<stdio.h>
void main()
{
int x=1;
int y;
for(x; x<=10;x=x+3)
{
y=x*x;
cout<<x<<end1<<y;
getch()
}

像这样的东西?您可以在此处找到有关流控制(如循环等)的更多信息:http://www.cplusplus.com/doc/tutorial/control/

帮助您朝着正确的方向前进。

for (int x = 1; stop condition; x += 3)
{
    doStuff();
}

此外,我不喜欢变量名x,因为它们不能解释它们的含义。