剛纔我剛剛開始學習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我看到很多關於將循環分解爲函數的建議,所以肯定會嘗試這樣做:) –