2012-10-07 66 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;