为什么我的变量没有初始化?

时间:2013-03-07 17:39:27

标签: c++ initialization

我只是从c转到C ++,我正在尝试构建一个计算器。 Int'结果'不会通过数学运算初始化。逻辑是,根据操作'',将有一个不同的值分配给'结果'。这似乎不起作用。

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

int main ()
{
    int n1, n2;
    char s,r;
    int result = 0;
    cout<< "Enter a calculation? (y/n)"<<endl;
    cin>>r;
    while(r=='y')
    {
        cout <<"Enter the first number"<<endl;
        cin>>n1;
        cout<<"Enter the operator"<<endl;
        cin>>s;
        cout<<"Enter the second number"<<endl;
        cin>>n2;

        if ('s' == '*')
        {
            result = n1*n2;
        }
        if ('s' =='+')
        {
            result = n1+n2;
        }

        if ('s' =='-')
        {
            result = n1-n2;
        }

        if ('s' =='/')
        {
            result = n1/n2;
        }
        cout << result<<endl;
        cout<< "Enter a calculation? (y/n)"<<endl;
        cin>>r;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:13)

svariable name,而's'(由单引号括起来)是character literal

这意味着,您必须与变量s进行比较,而不是's'。所以你的代码看起来应该是

if (s == '*')
{
    result = n1*n2;
}

代码

 if ('s' == '*')

将字符文字s与字符文字*进行比较,后者始终为false。

答案 1 :(得分:3)

@OlafDietsche没错。

我还建议切换到switch-case声明:

switch(s)
{
    case '*': result = n1*n2;  break;
    case '+': result = n1+n2;  break;
    case '-': result = n1-n2;  break;
    case '/': result = n1/n2;  break;
}