給定一個二維陣列,將所有不在二維陣列邊緣的數字相加。
示例二維陣列:
5 7 1 6
2 6 1 8
1 5 4 7
5 8 9 1
4 4 5 1
添加的數字應該只是6 1 5 4 8 9。
int rows, cols,s1=0,s2=0;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
printf("Elements:\n");
for(int row = 0; row < rows; row ){
for(int col = 0; col < cols; col ){
scanf("%d", &matrix[row][col]);
}
}
printf(Sum: %d", __);
......
uj5u.com熱心網友回復:
寫一個函式:
static int sum_middle(int rows, int cols, int matrix[rows][cols])
{
int sum = 0;
for (int r = 1; r < rows - 1; r )
{
for (int c = 1; c < cols - 1; c )
sum = matrix[r][c];
}
return sum;
}
然后在輸入回圈后呼叫它:
int sum = sum_middle(rows, cols, matrix);
uj5u.com熱心網友回復:
您可以更改輸入功能以計算總和:
int sum = 0;
for(int row = 0; row < rows; row ){
for(int col = 0; col < cols; col ){
scanf("%d", &matrix[row][col]);
if(
row && (rows > 2) && (row 1) != rows &&
col && (cols > 2) && (col 1) != cols
)
sum = matrix[row][col];
}
}
或者您可以在第二個回圈中執行此操作(請參閱@JonathanLeffler 的回答)。這將允許您只檢查一次行和列,而不是每次迭代(即,如果行 = INT_MAX 并且列是 0、1 或 2)。
uj5u.com熱心網友回復:
讓我用偽代碼解釋一下如何做到這一點:
您需要對所有未通過特定標準的數字求和。有兩種方法可以做到這一點:
- 將所有未通過特定條件的數字相加。如果標準不是太難,這可以做到。
- 將所有數字相加。將所有通過特定標準的數字相加,然后從第一個總和中減去。
讓我們看看我們是否可以通過第一種方式完成:我們首先將所有數字相加:
sum = 0
for i = 0 to a-1:
for j = 0 to b-1:
sum = matrix[i,j];
next j
next i
現在我們需要添加條件:
sum = 0
for i = 0 to a-1:
for j = 0 to b-1:
if not(criteria(i,j))
then sum = matrix[i,j];
next j
next i
但標準是什么:你怎么說(i,j) belongs to an edge?
嗯,這很簡單:邊緣意味著i等于0or a,并且j等于0or b:
所以你寫一個函式criteria(i,j)如下:
boolean criteria(i,j):
return ((i == 0) OR (i == a)) AND
((j == 0) OR (j == b));
或者,由于標準非常簡單,您甚至不需要為此使用函式:
sum = 0
for i = 0 to a-1:
for j = 0 to b-1:
if not(((i == 0) OR (i == a)) AND
((j == 0) OR (j == b)))
then sum = matrix[i,j];
next j
next i
但正如您所料,有一種更簡單的方法來撰寫標準,使用not(x AND y) = not(x) OR not(y)and not (x OR y) = not(x) AND not(y),但我把這個留給你:-)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/456450.html
上一篇:將csv從GCS上傳到BigQuery時,有沒有辦法提供架構或自動檢測架構?
下一篇:關于C結構中的記憶體管理的查詢
