首页 > 解决方案 > C++ - 构建加法表

问题描述

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

(从范围(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 = 范围内的最小数字,并且选择是用户执行加法表或乘法表的决定)。如何更改我的代码以适应正确的格式?我似乎无法弄清楚。任何提示/帮助将不胜感激:)

标签: c++loops

解决方案


#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
        }
    }

}

推荐阅读