Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C++中的嵌套for循环打印矩形_C++_Loops_Shape - Fatal编程技术网

用C++中的嵌套for循环打印矩形

用C++中的嵌套for循环打印矩形,c++,loops,shape,C++,Loops,Shape,我是编程的初学者 我目前正在编写一个代码,从用户那里获取行和列的数字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(

我是编程的初学者

我目前正在编写一个代码,从用户那里获取行和列的数字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;
}
我无法理解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) << " ";

我更喜欢使用计数器的显式版本,因为它可以清楚地显示您正在执行的操作,并且如果需要,您可以轻松地切换循环/输出的顺序。

这解决了值增量问题;你不妨尝试一下……对于个位数,也应该有一个0。
cout << (i*c + j + 1) << " ";