作業題:輸入4個整數,找出其中最大的數。用一個函數來實現. 分別使用結構化方法和函數嵌套的方法。
阿新 • • 發佈:2017-10-24
system 是否 進行 如果 div 使用 clu 函數 整型
之前在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; }
作業題:輸入4個整數,找出其中最大的數。用一個函數來實現. 分別使用結構化方法和函數嵌套的方法。