如何在C ++中的if ... then ...语句中使用变量?

时间:2012-10-07 23:37:58

标签: c++ variables if-statement

在C ++中,如何在if ... then ...或if?else或if ...语句中使用变量?

这就是我的意思。

当我输入这样的东西来制作计算器或其他东西时:

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 个答案:

答案 0 :(得分:0)

正如克里斯所说,你无法将字符串文字与整数进行比较。

如果你想比较一个字符(我猜你正在前进的地方),你想使用单引号,如if(d == '+')。字符的单引号,双引号在字符串上添加隐式的零终止。所以“+”实际上是{'+',0x0}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

将字符与变量进行比较时,必须在字符周围使用单引号。 例如

char mychar ='a';

if(mychar =='a')

cout&lt;&lt;“它的a”;

答案 3 :(得分:0)

if(d > 0) {

}

if(e < 0) {

}

答案 4 :(得分: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;