#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d);
int main()
{
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
int max_of_four(int a, int b, int c, int d)
{
if (a > b && a > c && a > d) {
printf("%d\n", a);
} else
if (b > a && b > c && b > d) {
printf("%d\n", b);
} else
if (c > a && c > b && c > d) {
printf("%d\n", c);
} else {
printf("%d\n", d);
}
return 0;
}
在這個問題中,我們必須使用函式找出 4 個數字中最大的數字。我的代碼有什么問題?為什么它沒有顯示正確的輸出?請告訴我我做錯了什么并糾正它。
uj5u.com熱心網友回復:
您的函式max_of_four沒有回傳最大數字,而是列印出一個數字并回傳 0。
在某些數字相同的情況下,您的代碼邏輯也是錯誤的(也許您想要>=而不是>處理這個問題)。
作為提示,如果您有一個max(a, b)回傳兩個數字的最大值的函式,您可以找到四個數字的最大值:
int max_of_four(int a, int b, int c, int d) {
return max(max(a, b), max(c, d));
}
這可能會對您有所幫助。
uj5u.com熱心網友回復:
Please tell me what I am doing wrong and please correct it.
問題出在你試圖撰寫過于復雜的錯綜復雜的代碼。
這是對函式的非常簡單的重寫(將 4 個值中的最大值回傳給呼叫者。)
int max_of_four( int a, int b, int c, int d ) {
int max = a;
if( b > max ) max = b;
if( c > max ) max = c;
if( d > max ) max = d;
return max;
}
保持簡單,錯誤讓您感到沮喪的機會更少。
uj5u.com熱心網友回復:
根據問題標題
撰寫一個函式 int max_of_four(int a, int b, int c, int d) 讀取四個引數并回傳其中最大的一個
該函式必須回傳最大值,但您的函式回傳 0。
int max_of_four(int a, int b, int c, int d)
{
//...
return 0;
}
此外,如果至少兩個引數具有最大值,您的函式將不輸出任何內容。
該功能可以看例如以下方式。
int max_of_four(int a, int b, int c, int d)
{
if ( !( a < b ) && !( a < c ) && !( a < d ) )
{
return a;
}
else if ( !( b < c ) && !( b < d ) )
{
return b;
}
else if ( !( c < d ) )
{
return c;
}
else
{
return d;
}
}
uj5u.com熱心網友回復:
據我說,這里的第一個答案是最好的。但不幸的是,我現在還不能投票。
無論如何,如果您正在撰寫一個函式來回傳四個數字中的最大數字,最好先宣告一個變數來存盤最大值,并將其初始化為 0(或者,您也可以將其初始化為給定的第一個數字給你)。
int max_of_four(int a, int b, int c, int d)
{
/*
Edit #1: Assigning the first value (among the four numbers) to
max is the best option. Please see below this code-box for
explanation. Thanks for pointing my mistake out, @Andrew Henle!
*/
max = a; //this will store the largest value eventually
if(b > max) //max is equal to "a" right now
max = b;
/*
if b is greater than the value stored in max, then replace max with b.
else, leave max as it is and proceed to the next line of code.
*/
if(c > max) //max has the largest number among a & b right now
max = c;
if(d > max) //max has the largest number among a, b, and c
max = d;
return(max); //the largest value among a,b,c,d will be returned
}
編輯:我最初假設你被要求只為正整數撰寫代碼。然而,正如Andrew Henle指出的那樣, max = 0不適用于負整數,因為負整數總是小于 0。因此,max = a是最好的方法。如果a是最大的值,那就太好了!如果不是,那么它最終會被其他更大的值替換,并且 max將存盤最大的數字。謝謝你,安德魯![嘿,這押韻!:) ]
其他人已經指出了您的編碼/邏輯錯誤,但這里有一個要點:
- 無論您在函式中寫什么,您的函式都回傳0 ,高于return 0;
- 當您的函式實際上應該回傳一個值時,它會不必要地列印一些數字。您實際上是將回傳值分配給另一個變數ans,對嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512660.html
標籤:Cif 语句最大限度函数定义
上一篇:Flutter>在View.builder中取消選擇RadioButton
下一篇:如何在c中縮短我的if陳述句?
