2013-01-31 132 views
2

嘿++刚开始这个星期所以我正在学习基本的C,我有一个问题,说:比较整数C++

编写一个程序来比较3个整数和打印最大的,程序应该只使用2 IF语句。

我不知道怎么做,所以任何帮助,将不胜感激

到目前为止,我有这样的:

#include <iostream> 

using namespace std; 

void main() 
{ 
int a, b, c; 

cout << "Please enter three integers: "; 
cin >> a >> b >> c; 

if (a > b && a > c) 
    cout << a; 
else if (b > c && b > a) 
    cout << b; 
else if (c > a && c > b) 
    cout << b; 

system("PAUSE"); 

} 
+0

这更多的是关于逻辑,而不是比较'C++'中的东西。无论哪种方式,我都不认为这是要问的地方。 – StoryTeller

+4

“void main()”...你用什么书来学习C++? – PlasmaHH

+0

nvm我看到答案波纹管 – TAM

回答

3

你不“如果别人”语句所需要的最后一个。在这部分代码中,肯定“c”是最大的 - 没有数字更大。

6
int main() 
{ 
    int a, b, c; 
    cout << "Please enter three integers: "; 
    cin >> a >> b >> c; 
    int big_int = a; 

    if (a < b) 
    { 
     big_int = b; 
    } 

    if (big_int < c) 
    { 
    big_int = c; 
    } 
    return 0; 
} 

另请注意,您应该写int main()而不是void main()

+0

感谢您的信息int main() – TAM

+0

欢迎您! – billz

4
#include <iostream> 
using namespace std; 

int main() 
{ 
    int a, b, c; 
    cout << "Please enter three integers: "; 
    cin >> a >> b >> c; 

    int max = a; 
    if (max < b) 
     max = b; 
    if (max < c) 
     max = c; 

    cout << max;  
} 

虽然上面的代码满足锻炼问题,我想我会添加一些其他方式来显示这样做没有任何if S的方式。

更神秘的,无法读取的方式,这是鼓励这么做,会

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

一种优雅的方式将

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

对于后者,则需要#include <algorithm>

+0

最后应该有一个'return'。 – Niko

+0

在C++中(不是C),在main函数中(并且仅在main函数中)省略return语句时,返回默认值0。 – legends2k

+0

http://stackoverflow.com/questions/22239/why-does-int-main-compile – legends2k

1

提示:您的if语句之一是无用的(实际上,它引入了一个错误,因为如果a,b和c都相等,则不会打印任何内容)。