刚才我刚刚开始学习C语言。今天,我得到了一个问题,我必须为2个矩阵(行和列的数量由用户指定)进行输入并添加它们。我很容易地做了添加和其他部分。但我正在考虑使它看起来更好的格式。 所以我的想法是: 假设用户输入一个3x3大小的矩阵。让我们假设他选择以下元素 - >一次打印两个数组,并且每次只能打印特定数量的字符
Matrix 1->
1 2 3
4 5 6
7 8 9
Matrix 2->
9 8 7
6 5 4
3 2 1
我要显示他们原样>
| 1 2 3 + 9 8 7 |
| 4 5 6 + 6 5 4 |
| 7 8 9 + 3 2 1 |
(不,不是实际添加,只是这种格式,然后在接下来的行我给答案补充)。 但问题是,我无法显示右侧的一半。
我的输出来如下:
| 1 2 3 + 9 8 7 |
| 4 5 6 + |
| 7 8 9 + |
我已经尝试了很多事情,使剩余的字符以正确的顺序显示,但有一些或其他类似的问题。到目前为止,这里是我的代码(它不是最近的,我试过把它弄得更糟糕,但是最新的代码甚至进一步混淆了它,引入了许多我认为甚至不需要的变量。所以我会发布我的迄今为止最好的进展)。
printf("| ");
i = 0; //A global int loop variable defined somewhere
width2 = width; //Another width variable in case I need it in second array, width is variable for number of elements in a row of array. In above example, width=3
for (ii = 0; ii < width * height; ii++) { //ii is just like i, another global int loop variable. Height is number of characters in a row (in above example 3)
if (ii != 0) {
if (ii % width == 0) {
printf(" |\n| ");
}
}
printf("%d ", row1[ii]); //For printing out first (left) set of numbers. row1 is where my matrix 1 array values are stored.
if (((ii + 1)*(width - 1)) % (width * 2) == 0) { //I think this condition is where things are going wrong.
printf(" + ");
for (i; i < width2; i++) {
if (i != 0) {
if (i % width2 == 0) {
printf(" |\n| ");
}
}
printf("%d ", row2[i]); //row2 has second matrix (right) array values
}
}
sec++; //Just another integer variable to have some control over loop process, didnt succeed much though
}
printf(" |\n\n");
从2天开始就尝试过,这真的让我很头疼。我不介意如果更好的更小的代码和整个代码需要被替换(因为我对C很新)。
它工作完美!非常感谢:D我看到很多关于将循环分解为函数的建议,所以肯定会尝试这样做:) –