找到最大数字的方法

时间:2012-06-28 11:55:52

标签: c++

目前我的迷你算法看起来像这样。

int a,b,c,max;
cout <<"Enter 3 digits: \t";
cin>>a>>b>>c;
if(a>b && a>c)
    max=a;
else if(b>c && b>a)
    max=b;
else
    max=c;
cout <<"max: "<<max<<endl;

它有效但有没有其他方法可以找到最多3位数?

6 个答案:

答案 0 :(得分:4)

在C ++ 11中,你可以这样做:

int max_value = std::max({a, b, c});

它使用std::max的重载,以std::initializer_list<T>为参数。这意味着您可以传递超过3个参数

int max_value = std::max({1,2,3,4,5,6,98,10});

演示:http://ideone.com/FLifw

答案 1 :(得分:2)

int max = std::max( std::max( a, b ), c );

对于,您可以编写自己的max函数或使用MAX宏(在标准中定义,但可能由编译器“支持” )

答案 2 :(得分:2)

max = a; 
if(b>max) max = b;
if(c>max) max = c;

这会有用吗?

答案 3 :(得分:0)

在C ++中,您应该使用std::max()

const int max_value = std::max(std::max(a, b), c);

答案 4 :(得分:0)

int max=a>b?(a>c?a:c):(b>c?b:c);

printf("greatest no: %d"(a>b)?((a>c)?a:c):((c>b)?c:b)); 

答案 5 :(得分:0)

.SaveChanges()