繁体   English   中英

在C ++中将数字打印为带有嵌套for循环的矩形

[英]printing numbers as a rectangle with nested for loops in c++

我是编程的初学者。

我目前正在编写一个代码,该代码接受用户的行数和列数为1到9。 对于一个数字,应该有一个“ 0”

输出应如下所示:

Type a row number between 1 and 9: 3
Type a column number between 1 and 9:7
01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21

这是我目前拥有的代码:

#include <iostream>


int main() {
    int r,c,i,j,n,k;
    cout<<"Type a row number between 1 and 9: ";
    cin>>r;
    while (r<1 || r>9){
        cout << "Please enter a number between 1 and 9.";
        cin>>r;
    }
    cout<< "Type a column number between 1 and 9: ";
    cin>>c;
    while (c<1 || c>9){
        cout << "Please enter a number between 1 and 9.";
        cin>>c;
    }

    n=r*c;

    for(k=0; k<n; k++){
    }

    for(i=0; i<r; i++)
    {
        for(j=0; j<c; j++)
        {
            cout<<i<<" ";
        }       
        cout << endl;
    }

    return 0;
}

我为用户添加了有效性声明。

输出:

Type a row number between 1 and 9: 3
Type a column number between 1 and 9:7
0 0 0 0 0 0 0
1 1 1 1 1 1 1
2 2 2 2 2 2 2 

我不知道0和如何将数字实现到矩形中。

请帮忙。

您接近了,只需将输出循环更改为:

int counter = 1;

for (i = 0; i < r; i++)
{
    for (j = 0; j < c; j++)
    {
        cout << counter << " ";
        ++counter;
    }       
    cout << endl;
}

如果您想避免多余的局部变量,也可以执行以下操作:

cout << (i*c + j + 1) << " ";

我更喜欢使用counter的显式版本,因为它可以使您清楚自己在做什么,并且可以根据需要轻松地切换循环/输出的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM