注意:本教程針對正在學習 C++ 和程式設計的初學者。
如何使用 C++ 程式語言獲取 3 個數中的最大值。
當然,你可以用很多方法獲取 3 個數中的最大值,事實上,可以有不止一個解決方案,而且它們都是正確的,但對於這個問題,我發現了一個非常有趣的解決方案。
這是程式碼,我將在下面解釋它
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
/* Function maximum definition */
/* x, y and z are parameters */
int maximum(int x, int y, int z) {
int max = x; /* assume x is the largest */
if (y > max) { /* if y is larger than max, assign y to max */
max = y;
} /* end if */
if (z > max) { /* if z is larger than max, assign z to max */
max = z;
} /* end if */
return max; /* max is the largest value */
} /* end function maximum */
|
程式碼非常簡單,它假設 3 個值中的任何一個都是最大的,然後將其他 2 個值與第一個值進行比較。
如果 2 個值中的一個大於我們假設的值,則最大值等於該值。
如果您對本文有任何疑問,可以透過以下方式聯絡我:
Twitter: _mFouad
郵件: mfouad91@gmail.com