C ++-建立加法表

时间:2018-09-09 03:08:41

标签: c++ loops

我在实验室提出的这个问题上遇到了一些麻烦。我的目标是产生一个看起来像这样的加法表-

(范围(1-5)):

+    1    2    3    4    5
1    2    3    4    5    6   
2    3    4    5    6    7
3    4    5    6    7    8
4    5    6    7    8    9
5    6    7    8    9    10

我的看起来像这样:

+    1    2    3    4    5
     2    3    4    5    6
     3    4    5    6    7
     4    5    6    7    8
     5    6    7    8    9

我的代码如下:

if (choice == ADD) {
    cout << "+";
    for (int i = 0; i < max; i++) {
        cout << "\t";
        for (int j = min; j <= max; j++) {
            cout << i + j << "\t";
        }
    }
}

(作为参考,int max =范围内的最大数,int min =范围内的最小数,由用户决定是做加法表还是乘法表)。如何更改代码以适合正确的格式?我似乎无法弄清楚。任何提示/帮助将不胜感激:)

2 个答案:

答案 0 :(得分:0)

#include <iostream>

using namespace std;

int main(){
    int max = 5;
    int min = 1;

    if (true){
        cout << "+\t";//print out the initial +
        for(int i = min; i <= max; i++) cout << i << "\t";//print out the entire first row
        cout << "\n"; //start the next row

        //here is the main loop where you do most of the logic
        for(int i = min; i <= max; i++){
            cout << i << "\t"; //this prints out the first column of numbers
            for(int j = min; j <=max; j++){
                cout << j+i << "\t"; //this line fills in the body of your table
            }
            cout << "\n";//creates the space between each row
        }
    }

}

答案 1 :(得分:0)

此代码按照说明构建表:

for (int i = 0; i <= max; i++) {
    if (i == 0)
        cout << '+';
    else
        cout << i;

    cout << '\t';
    for (int j = min; j <= max; j++) {
        cout << i + j << '\t';
    }
    cout << '\n';
}

提示:当您只想打印字符时,使用'+''\t'之类的单引号会更有效。双引号更昂贵,因为它们代表const char*