如何使用if语句输出此乘法表?

时间:2015-02-26 22:19:24

标签: c++ arrays if-statement multiplication n-dimensional

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main()
{
    char response = 'y';
    while (response == 'y')
        do
        {
        const int myarray = 144;
        int thearray[myarray];
        for (int m = 0; m < 12; m++)
        {
            cout << m + 1 << " ";
        }
        cout << endl;
        for (int rown = 1; rown < 11; rown++)
            for (int n = 0; n < 12; n++)
            {
                thearray[(rown * 12) + n] = thearray[n] * (rown + 1);
            }
        if ()
    cout << "Would you like to run the program again? \n"
        << "Enter y for yes or n for no: ";
    cin >> response;
} while (response == 'Y' || response == 'y');
return 0;
}

此代码的要点是使用1维数组来创建乘法表。我相信我的所有代码都是正确的,但是这个赋值的另一部分是使用if语句输出表,而我并不完全确定如何。有人可以给我一些指导吗?

1 个答案:

答案 0 :(得分:0)

我不知道C的功能,但我认为它会像这样工作(只考虑过程/逻辑,而不是实际的代码)

nums = array(1, 2, 3, 4, 5)
output space for left display column of numbers
foreach (nums as header) { // this hopefully builds the top of the table
  output header; // column header
}
for each (nums as row) { // this will go through 1,2,3,4,5 
  if (nums === multiplier) output left row label // i.e "1 | "
  for each (nums as col) {       
    output (row * col) // multiply row * col and display it
  }
}

否如果需要声明......希望有所帮助。 对不起,如果代码不完整,我就不用编程了。

编辑:

为了理智,我写了一些似乎有用的东西。总是很高兴学习新语言:) ....让我知道你的想法。

https://ideone.com/Id9Ax9

这是我提出的为我工作的代码

#include <iostream>
using namespace std;
int main() {
// Define variables
    int nums [5] = { 1, 2, 3, 4, 5};
    // set default values
    string headerRow = "    ";
    string rowLabel = "";
    string currentRow = "";
    string currentVal = "";
    // start the process
    int maxArray = (sizeof(nums)/sizeof(nums[0]));
    for (int i=1; i<=maxArray; i++) { headerRow = headerRow + to_string(i) + "  "; }
    cout << headerRow + "\n"; // Display header row
    cout << "    ---------------\n";
    for (int r=1; r<=maxArray; r++) { // this will cycle through rows 1,2,3,4,5 
        currentRow = "";
        for (int c=1; c<=maxArray; c++) {// this will cycle through columns 1,2,3,4,5 
            if (r == c) {
                rowLabel = to_string(r) + std::string(" | "); 
            }
            currentVal = to_string(c * r) + "  "; // multiply row * col and display it
            currentRow = currentRow + currentVal;
        }    
        cout << rowLabel + currentRow + "\n";
    }
}
相关问题