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

Why is my variable not initializing?

本文关键字:初始化 变量 我的 为什么      更新时间:2023-10-16

我只是从c移动到c++,我试图建立一个计算器。Int 'result'不会被数学运算初始化。逻辑是,根据操作's',将有一个不同的值分配给'result'。这似乎行不通。

#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;
}

s是一个变量名,'s'(用单引号括起来)是一个字符字面值。

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

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

代码

 if ('s' == '*')

比较字符字面量s和字符字面量*,这总是假的。

@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;
}