2012-10-07 70 views
-2

在C++中,如何在if ... then ...或if ... else或if ...語句中使用變量?如何在C++中使用if ... then ...語句中的變量?

這是我的意思。

當我進入這樣的事情做一個計算器或東西:

int main() 
{ 
    signed int a, b, c, d, e result; 
    cin >> a; 
    cin >> b; 
    cin >> c; 
    cin >> d; 
    cin >> e; 

    if(d=="+") 
    if(e=="-") 
     result = a + b - c 
    cout <<result; 
} 

它不工作。

我在做什麼錯?

+5

'D'是一個整數,而不是字符串。 'e'也一樣。 – chris

+1

爲了在提問時獲得更好的結果,請發佈完整的編譯器錯誤並指出它們所在的行。 – chris

+0

那麼我該如何解決這個問題呢? –

回答

0

正如chris所說,你不能將字符串文字與一個整數進行比較。

如果你要比較單一字符(我猜這就是你的標題),你想使用單引號,像這樣if(d == '+')。字符的單引號,雙引號在字符串上添加隱式零終止。所以「+」實際上是{'+',0x0}

+0

那麼我應該如何解決這個問題呢? –

+0

我編輯了一個答案:使用單引號。 –

+0

哎呦,對不起,我沒有注意到。謝謝。 –

0
int main() 
{ 
signed int a, b, c,result; 
char d,e; 
    cin >> a; 
    cin >> b; 
    cin >> c; 
    cin >> d; 
    cin >> e; 

if(d=='+') 
    if(e=='-') 
    result = a + b - c 
cout <<result; 
} 
0

當比較一個字符和一個變量時,你必須在字符周圍使用單引號。 例如:

char mychar ='a';

如果(mychar == 'A')

COUT < < 「的一個」;

0
if(d > 0) { 

} 

if(e < 0) { 

} 
0
int main() 
{ 
int a, b, c,result; // you don't need write signed because it's by default signed 
char d,e; 
    cin >> a; 
    cin >> b; 
    cin >> c; 
    cin >> d; 
    cin >> e; 

if(d=='+'){ // good practice to put {}. if you'll put another line of code in the future 
    if(e=='-'){ 
    result = a + b - c; //you forgot statement ";" 
    } 
} 
cout <<result;