为什么我的变量没有初始化?
问题描述:
我只是从C移到C++,并且正在尝试构建计算器。诠释'结果'不会初始化与数学运算。逻辑是,根据操作的''将有一个不同的值分配给'结果'。这似乎并不奏效。为什么我的变量没有初始化?
#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'
。所以,你的代码看起来应该像
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;
}
+0
+1非常好的建议。 – 2013-03-07 17:55:19
你怎么知道*** ***结果未初始化?你有什么证据?你的投入是什么,你期望什么产出与你实际看到的是什么? – abelenky 2013-03-07 17:40:54
*“这似乎不起作用。”*为什么?有什么问题? – m0skit0 2013-03-07 17:41:28
Aww,这个伤害。 – 2013-03-07 17:42:36