【发布时间】:2015-04-17 08:44:54
【问题描述】:
我刚刚开始学习 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 很陌生)。
【问题讨论】:
标签: c arrays nested-loops