如果否则错误:如何使其打印任何数字
If else error : How to make it print with any number?
代码应将负数转换为 0。
负数有效,但正数不起作用
int main() {
int userNum = 0;
if (userNum >= 0)
cout << "Non-negative" << endl;
else
cout << "Negative; converting to 0" << endl;
userNum = 0;
cout << "Final: " << userNum << endl;
return 0;
}
用户使用 99 时的预期输出
Non-negative
Final: 99
在
打印Final
消息之前,您将无条件地将userNum
设置为 0,而不考虑其以前的值。 这是因为您的else
块缺少一组大括号:
int main() {
int userNum = 0;
cout << "Enter a number: ";
cin >> userNum;
if (userNum >= 0)
cout << "Non-negative" << endl;
else
{ // <-- add this!
cout << "Negative; converting to 0" << endl;
userNum = 0;
} // <-- add this!
cout << "Final: " << userNum << endl;
return 0;
}
相关文章:
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- 在数字之间插入 + 或 - 符号以使其等于整数
- C++中的双边友语函数:如何使其编译?
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何使代码打印文本文件中的第一行?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- 更改高度贴图,使其在 4x4 网格上显示 16 个 hieghtmap
- 提升库,使其成为C++标准
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 如何修复阵列以使其正确?
- 设置我的应用程序 API 感知并防止系统使其模糊和错误定位
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 如何通过按 F2 或 F3 等键使控制台打印某些内容
- C++如何简化此模板以使其不专业?
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 如何使"static_assert"打印失败时获得的值?
- 以编程方式防止重命名或删除文件,但仍使其可写
- 如果否则错误:如何使其打印任何数字
- 我怎样才能打印每个阶段下的数字并使其整洁