C/C++ 求最大值方法

很多方面C语言和C++都很相似.

1.一般法(条件表达式)——直接在main函数中运算

特点:简短清晰

#include <iostream>
using namespace std;
int main(void){
    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(void){
    //当数据只有两个时调用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>
using namespace std;
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(void){
    int a,b,c;
    cin>>a>>b>>c;
    cout<<getMax_3(a,b,c)<<endl;
    return 0;
}

总结:通过求最大值问题引入三种方法,旨在对同一问题能够分情况考虑,当项目规模小时可以考虑方法一方法二,当项目大时建议考虑方法三 .

猜你喜欢

转载自blog.csdn.net/Liang_xj/article/details/82929656