为什么我的变量没有初始化
Why is my variable not initializing?
我只是从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;
}
相关文章:
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- 在 C++ 中访问 lambda 捕获初始化变量
- 为什么C++不支持对未初始化变量进行智能分析?
- 使用 clang++ 和 g++ 在C++中初始化变量
- C++使用 lambda 初始化变量
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++ - 输出与初始化变量不同?
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- C++ 中的初始化变量
- C++中未初始化变量的值
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 我想知道在构造函数中初始化变量时的生命周期
- 读取恰好具有良好值的未初始化变量
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 为什么在 c++ 中有多种初始化变量的方法
- 没有参数的默认构造函数是否总是初始化变量?
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 使用构造函数跳闸UB的新放置后使用初始化变量