求10 個整數中最大值。

2021-09-12 23:16:44 字數 1530 閱讀 6321

求10 個整數中最大值。

#define _crt_secure_no_warnings

#include int main()

max = a[0];

for (i = 0; i < 10; i++)

else

} printf("這十個整數的最大值是:%d\n", max);

system("pause");

}

程式設計思路:

首先從鍵入十個整數;(由於數值較多,我採用建立陣列來存放這十個數)

其次,找到最大值。(我假定第乙個數是最大的,令max=a[0],再採用迴圈,接著採用if選擇語句,讓每個數與a[0]比較,直至找到最大的數字)

最後輸出這個最大值。

難度公升級:求出最大數和次大數字:

若要找出次大數,我們首先定義第乙個數最大第二個數次大,當有第三個數傳進來以後會出現三種情況

1)第三個數最小;

2)第三個數最大;

3)第三個數在中間。

情況一,我們可以直接丟掉第三個數,遍歷下個數字進行比較;

情況二,我們丟掉第一次的次大數,並把原來的最大數賦值給次大,第三個數賦值給最大數;

情況三,我們將第三個數直接設為次打數,原來的次大數直接丟掉就哈。

**如下:

#define _crt_secure_no_warnings

#include int main()

max = a[1];

next = a[2];

if (next > max)

for (i = 3; i < 11; i++)

else if (a[i]>next)

} printf("max=%d\tnext=%d\n", max, next);

system("pause");

return 0;

}

若是難以理解也沒有關係,我們還可以換個角度來思考,從另外一種角度來寫**:

#define _crt_secure_no_warnings

#include int main()

max = a[1];

next = a[2];

if (next > max)

#if 0

for (i = 3; i < 11; i++)

else if (a[i]>next)

} printf("max=%d\tnext=%d\n", max, next);

#else

for (i = 3; i<11; i++)

else if (a[i] > next)

else

}#endif

system("pause");

return 0;

}

注意此處的#if 0/1 +#else+#endif可以理解為注釋的開關,可以幫助我們更好的理解此程式的執行機理,(僅供參考)

求10 個整數中最大值

題目 求10 個整數中最大值 分析 可以預設第乙個數為最大,用max儲存最大數字,然後每輸入乙個數字,就與max進行比較,不斷更新max的值。最後max中儲存的值就是最大數字。這裡10個整數可以不用陣列儲存,逐一輸入比較 也可以用陣列儲存,然後遍歷比較。define crt secure no wa...

C語言 求10 個整數中最大值

求10個整數中的最大值。先建立乙個能夠儲存10個資料的陣列,輸入資料,將第乙個值賦給變數max,然後依次將陣列中的每乙個數與max比較,當max小於對應的數時,則將對應的數賦給max,10個值全部執行完畢之後,max中便是這是個值中最大的值,輸出max即可。define crt secure no ...

Problem A 求個最大值

time limit 1 sec memory limit 128 mb submit 1635 solved 1339 submit status web board 定義maxvalue類,用於求一系列非零整數的最大值。其中 1.資料成員elements用於儲存所有輸入的非零整數。3.int g...