for循环到while转换

时间:2018-09-08 14:31:00

标签: c++ loops for-loop while-loop

在这里,我有一个带有for循环的C ++代码。

for(int A=1;A<=3;A++)
    {
     cout<<A*2;
     for(int B=1;B<=A;B++)
     cout<<"*";
     cout<<endl;
    }

它给了我这个输出。

2 * 4 ** 6 ***

我需要使用while循环做同样的事情。所以我将上面的代码转换为此代码。

while(A<=3)
    {
    cout<<A*2;
        while(A>=B)
        {cout<<"*";
            B++;}

    cout<<endl;
    A++;
    }

但是这段代码给了我输出 2 * 4 * 6 *

有人可以告诉我在while循环中我在做什么错。

5 个答案:

答案 0 :(得分:3)

int A = 1;
int B;

while (A <= 3)
{
    cout << A * 2;
    B = 1;
    while (B <= A)
    {
        cout.put('*');
        ++B;
    }

    cout.put('\n');
    ++A;
}

ioccc样式:

#include <iostream>

int main()
{
    int A{1};while(!(A>>2)&&std::cout.put((A<<1)|0x30)){
        int B{A++};while(std::cout.put((!B)["*\n"]),B--);}
}

答案 1 :(得分:2)

您没有给出A或B的初始值。

void func()
{
    int A = 1;
    while (A<=3)
    {
        std::cout << A*2;
        int B = 1;
        while(A>=B)
        {
            std::cout << "*";
            B++;
        }

        std::cout<<endl;
        A++;
    }
}

答案 2 :(得分:0)

您的第二个片段不显示您声明AB的位置。我假设它在外部while循环之外,无法正常工作。您必须在第一个while内声明B或在每个循环中重新初始化它。

int A = 1;
while(A <= 3)
{
  cout << A * 2;
  int B = 1;
  while(A >= B)
  {
    cout << "*";
    ++B;
  }
  ++A;
  cout << endl;
}

Result

答案 3 :(得分:0)

您应将B用作局部变量,然后将while的比较值更改为小于和等于。

int A = 1;

while(A<=3) {
    cout<<A*2;
    int B = 1; // B as local variable
    while(B<=A) {
        cout<<"*";
        B++;
    }
    cout<<endl;
    A++;
}

输出:

2 *
4 **
6 ***

答案 4 :(得分:0)

int A = 1;
while(A <= 3)
{
    cout<<A*2;
    int B = 1;
    while(A >= B){
        cout<<"*";
        B++;
    }
    cout<<"/n";
    A++;
}

输出:
2 *
4 **
6 ***