(1)笨办法,采用if嵌套和&&判断,比较消耗资源,不过也能达到要求:
#include<iostream> using namespace std; int main() { int a,b,c,max; cout<<"please input 3 numbers:"<<endl; cin>>a>>b>>c; if(a>b&&a>c) max=a; else if(b>c&&b>a) max=b; else max=c; cout<<a<<" "<<b<<" "<<c<<" "<<"三个数中,最大的是:"<<max<<endl; return 0; }
(2)采用三目运算符,程序变得简便许多:
#include<iostream> using namespace std; int main() { int a,b,c,max; cout<<"please input 3 numbers:"<<endl; cin>>a>>b>>c; max=(a>b)?a:b; if(c>max) max=c; cout<<a<<" "<<b<<" "<<c<<" "<<"最大的数为: "<<max<<endl; return 0; }
(3)调用一个函数:
#include<iostream> using namespace std; int maxNum(int,int,int); int main() { int a,b,c,max; cout<<"please input 3 numbers:"<<endl; cin>>a>>b>>c; max=maxNum(a,b,c);//调用函数 cout<<a<<" "<<b<<" "<<c<<" "<<"最大的数为: "<<max<<endl; return 0; } int maxNum(int a,int b,int c)//不要忘记参数定义 { if(a>=b&&a>=c) return a; else if(b>=a&&b>=c) return b; else return c; } //int numMax(int x,int y,int z) //{ // int max; // //max=(x>y)?x:y; // //if(z>max) // // max=z; // //return max; // if(x>=y&&x>=z) // { // max=x; // }else if(y>=x&&y>=z) // { // max=y; // }else // { // max=z; // } // return max; //}