讀入 m×n 矩陣,找出絕對值最大的元素,輸出其行號、列號(從 1 開始)及原值。若全為 0 輸出 1 1 0。多測試用例。
#include <iostream> #include <cmath> using namespace std; int main() { int m, n; while (cin >> m >> n) { int max = 0, column = 0, row = 0, a; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { cin >> a; if (abs(a) > abs(max)) { max = a; column = i; row = j; } } } if (max == 0) cout << "1 1 0" << endl; else cout << column << " " << row << " " << max << endl; } return 0; }
max=0:配合 abs(a) > abs(max),天然處理全零矩陣(最大值保持 0,座標 (0,0) 後修正為 (1,1))。i=1..m, j=1..n 直接對應輸出要求。max = a 而非 abs(a),輸出時保留符號。abs() 需 <cmath>(C++)或 <stdlib.h>(C)。| 輸入 | 輸出 | 說明 |
|---|---|---|
2 2 | 1 1 0 | 全零特判 |
2 2 | 1 1 -5 | 負數絕對值最大,輸出原值 -5 |
3 3 | 2 2 -10 | 中間元素絕對值最大 |