C/C++ 求最大值方法
阿新 • • 發佈:2018-12-13
很多方面C語言和C++都很相似.
1.一般法(條件表示式)——直接在main函式中運算
特點:簡短清晰,主要用在不常求最大值的情況
#include <iostream> using namespace std; int main(){ int a,b,c,max;//max用了存放最大值 cin>>a>>b>>c; max=(a>=b&&a>=c)?a:(b>=a&&b>=c)?b:c; /*上述條件表示式轉化為if-else表示式如下: if(a>=b&&a>=c) max=a; else if(b>=a&&b>=c) max=b; else max=c; */ cout<<max<<endl; return 0; }
2.函式呼叫
特點:相對一般法,在需要時函式可以反覆呼叫而不用每次都要重寫一遍。並且涉及比較個數問題我們引入過載 . 當資料較大時,把資料載入陣列有效減少程式碼量.
#include <iostream> using namespace std; int getMax(int a,int b){ return a>b?a:b; } int getMax(int array[],int count){//count表示陣列長度 int max=array[0]; for(int i=0;i<count;i++) if(max<array[i]) max=array[i]; return max; int main(){ //當資料只有兩個時呼叫int getMax(int a;int b);資料大於兩個時可以先將所有資料存到陣列作為引數呼叫int getMax(int array[],int count); int arr[10]={34,12,3,78}; cout<<getMax(3,5)<<endl; cout<<getMax(arr,4)<<endl; return 0; }
3.函式的巢狀呼叫
函式的巢狀呼叫是指在一個函式中呼叫另一個函式,呼叫方式和在main函式呼叫其他函式是一樣的 .
特點:程式碼條理清晰
#include <iostream> int getMax_2(int a,int b){ return a>b?a:b; } int getMax_3(int a,int b,int c){ int temp=getMax_2(a,b); temp=getMax_2(temp,c); return temp; } int main(){ int a,b,c; cin>>a>>b>>c; cout<<getMax_3(a,b,c)<<endl; return 0; }
總結:通過求最大值問題引入三種方法,旨在對同一問題能夠分情況考慮,當專案規模小時可以考慮方法一方法二,當專案大時建議考慮方法三 .