Write a C++ program using nested loops to output the following numbers to the screen?

时间:2015-05-24 22:17:34

标签: c++ nested-loops

I wrote a C++ program, but the output I got was unexpected (as shown below).

enter image description here

#include<stdio.h>
#include<iostream>
#include<iomanip>
using namespace std;
main()
{
int a,b;
for(a=3;a<=21;a+=2)
    {
    printf("\n");
    for(b=1;b<a;b+=2)
        {
        cout<<setw(2)<<a+b-1<<" ";
        }
    }
cout<<"\n";
}

Can someone help me tweak it, so it runs like this:

enter image description here

5 个答案:

答案 0 :(得分:2)

#include <iostream>

using namespace std;

int main(int, char**)
{
    int i = 3;
    int numcols = 1;

    while(i <= 21)
    {
        int j = 0;
        for(j = 0; j < numcols; j++)
        {
            cout << i + j << '\t';
        }
        cout << '\n';
        i += 2;
        numcols += 1;
    }
}

如果tab太宽,您可以用双倍空格替换它。

答案 1 :(得分:1)

捕捉!

#include <iostream>
#include <iomanip>

int main() 
{
    while ( true )
    {
        const size_t N = 24;

        std::cout << "Enter a non-negative number less than " << N << " (0 - exit): ";

        size_t n = 0;
        std::cin >> n;

        if ( !n ) break;

        if ( N < n  ) n = N;

        std::cout << std::endl;

        for ( size_t i = 0, x = 3; i < n; i++, x += 2 )
        {
            for ( size_t j = 0; j <= i; j++ ) std::cout << std::setw( 4 ) << x + j;
            std::cout << std::endl;
        }

        std::cout << std::endl;
    }

    return 0;
}

如果输入10则输出

Enter a non-negative number less than 24 (0 - exit): 10
   3
   5   6
   7   8   9
   9  10  11  12
  11  12  13  14  15
  13  14  15  16  17  18
  15  16  17  18  19  20  21
  17  18  19  20  21  22  23  24
  19  20  21  22  23  24  25  26  27
  21  22  23  24  25  26  27  28  29  30

Enter a non-negative number less than 24 (0 - exit): 0

循环也可以按以下方式编写

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j <= i; j++ )
        {
            std::cout << std::setw( 4 ) << 2 * i + 3 + j;
        }
        std::cout << std::endl;
    }

答案 2 :(得分:1)

这是你想要达到的目标吗?

#include<stdio.h>
#include<iostream>
#include<iomanip>
using namespace std;
main()
{
int a,b;
for(a = 1 ;a <= 10; a++)
{
    for(b = 2 * a + 1;b <= 3 * a; b++)
    {
        cout<<setw(2)<<b<<" ";
    }
    printf("\n");
}
cout<<"\n";
}

答案 3 :(得分:0)

int a,b = 0;
for(a=3;a<=21;a+=2)
{
    printf("\n");
    b++;
    for(int i =0;i < b;i++)
    {
        cout<<setw(2)<<a+i<<" ";
    }

在内部循环之外增加b,这样您就可以计算每行所需的数量。

答案 4 :(得分:0)

如果你看第二个循环,你可以从1开始,如果你将它设置为b = a,它将帮助你分配,因为你只需要有std :: cout&lt;

以上内容可能是您需要做出的唯一改变。