作業題:輸入4個整數,找出其中最大的數。用一個函數來實現. 分別使用結構化方法和函數嵌套的方法。


之前在main()函數中的思路是:

#include <iostream>
using namespace std;



int main(){
    //求四個數中最大的數? 
    //思路: 三元運算符反復比較的方法。 

    int a,b,c,d,max;
    cout<<"請你輸入四個整型的數字:"<<endl;
    cin>>a>>b>>c>>d;
    max=a>=b?a:b;
    max=max>=c?max:c;
    max=max>=d?max:d;
    cout<<"The max of them is:"<<max<<endl;
    //system("pause");
    return 0;
}

用函數嵌套的方法來實現求四個數中最大的數?

#include <iostream>
using namespace std;

int max4(int o ,int p,int r,int q);
int max2(int x,int y);

int main(){
    //求四個數中最大的數? 
    //思路: 使用求2個數最大值的函數進行反復比較的方法。 

    int a,b,c,d,max;
    cout<<"請你輸入四個整型的數字:"<<endl;
    cin>>a>>b>>c>>d;
    max=max4(a,b,c,d);
    cout<<"The max of them is:"<<max<<endl;
    //system("pause");
    return 0;
}
//首先確定函數是否需要返回值?需要返回值的話要寫返回值類型 如果不需要返回值則寫void 
int max4(int o ,int p,int r,int q){//形式參數 //變量的生命周期 接收實際參數的賦值 int x=a,int y=b; 
    int m;
    m=max2(o,p);
    m=max2(m,r);
    m=max2(m,q);
    return m;
}
int max2(int x,int y){
    return x>y?x:y;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM