C ++ if else 语句在开关大小写 - 解释
c++ if else statement in switch case - explanation
刚开始学习。我有一个关于开关语句中是否还有其他问题
这是代码
switch (operation)
{
case '+':
result = num1 + num2;
cout << result << endl;
break;
case '-':
result= num1-num2; cout << result<< endl; break;
case '*':
result= num1 * num2;
cout << result<< endl;
break;
case '/':
if (num2 == 0)
{
cout << "num2 cannot be zero - division with zero is not possible!n";
}else{
result= num1/num2;
}
cout << result << endl;
break;
default:
cout << "message!" << endl;
break;
}
好的,此代码正在生成错误 - 运行时检查失败 #3 - 变量"result"未初始化而被使用。
如果我更改代码并在 Nessage 之后添加中断,则无法用 0 除法
case '/':
if (num2 == 0)
{
cout << "num2 cannot be zero - division with zero is not possible!n"; break;
}else{
rezultat = num1/num2;
}
cout << rezultat << endl;
break;
一切都按预期工作。
谁能从程序逻辑方面澄清这里发生了什么? 这是否意味着即使满足条件,if语句的else块也在运行?
提前感谢!
因为如果0
num2
则打印消息,然后尝试执行cout << result << endl;
,结果仍未初始化
另一个可能的解决方法是:
case '/':
if (num2 == 0)
{
cout << "num2 cannot be zero - division with zero is not possible!n";
}else{
result= num1/num2;
cout << result << endl;
}
break;
在您的原始代码中,如果num2 == 0
,则您的消息将发送到 cout
,但result
没有被分配值。执行继续,紧跟在else
块之后的行:
cout << result << endl;
从而生成错误。
在修改后的代码中,如果num2 == 0
则行上的两个语句
cout << "num2 cannot be zero - division with zero is not possible!n"; break;
被处决。break;
语句会导致在整个switch
块结束后继续执行,因此cout << rezultat << endl;
永远不会被执行。
希望在上面澄清您的问题,但您可能会删除多余的 从语句Switch
cout<<result<<endl;
并将其放在相同的语句之外,因为它是所有case
中的公共部分,除了显示计算结果外什么都不做,类似于
switch(operation)
{
case '+': /*your computation here*/ break;
case '-': /*your computation here*/ break;
case '*': /*your computation here*/ break;
case '/': /*your computation here*/ break;
default: /*your message command here*/;
}
cout<<result<<endl; /* since this line is common, and does nothing but prints the result */
相关文章:
- 无法找到简单的开关大小写枚举错误
- 如何在不同的开关大小写语句上使用对象的类成员函数?
- 在这种情况下,如何在基类中设计开关大小写函数
- 无法在开关大小写中调用函数 - C++
- 开关大小写始终为默认值
- 使用开关大小写语句抽取随机扑克牌等级和花色以显示用户
- C++:如果用户输入数字将其转换为单词,并且如果按回车键程序应退出,则使用开关大小写
- C ++使用开关/大小写解析protobuf消息(减少重复代码)
- C++函数中未定义的开关大小写
- 开关大小写不调用其中的函数
- 为什么我的代码在开关大小写中不起作用
- 开关大小写语句中函数中的字符串输入会导致无限循环和绕过输入
- 使用 std::string 返回开关大小写块中的字符串常量
- 如何在开关大小写中使用字符
- Rapidjson::Type的开关大小写.我尝试解析的
- 开关大小写错误 |的值在常量表达式中不可用
- 使用 map<string,int> 在开关大小写语句中使用字符串
- C++ 带有终止字符的开关大小写计算器
- 如何在用户提示下在开关大小写实现中退出
- 开关大小写程序在某个点上保持循环.想不通