2013-01-31 43 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都相等,則不會打印任何內容)。