c++ - 变量可能未初始化/未初始化使用
问题描述
我正在用 C++ 编写一个英制转换器程序,并且我正在尝试使用 try、throw、catch 来拒绝“main”函数中的负数/非数字值。
我的两个问题是:
1.) 每当我在控制台中输入“g”时,我都会得到一个输出:0 英寸等于 0 厘米,然后我会得到我想要弹出的错误显示。我需要的只是要输出的错误显示。
2.)当我输入一个负数时,比如 -3,当我希望它告诉我我的输入无效时,我会得到正确的转换为负数。
这是我的代码。
#include <iostream>
#include <cctype>
char menuSelect();
using namespace std;
int main(int argc, const char * argv[])
{
double inches;
double centimeters;
char select;
try
{
do
{
if (centimeters < 0.0 || inches < 0.0)
throw 0;
if (!cin)
throw 0;
select = menuSelect();
if (select == 'E')
{
cout << "Enter the number of inches: ";
cin >> inches;
centimeters = inches * 2.54;
cout << inches << " inches is equal to " << centimeters
<< " centimeters." << endl;
}
else if (select == 'M')
{
cout << "Enter the number of centimeters: ";
cin >> centimeters;
inches = centimeters / 2.54;
cout << centimeters << " Centimeters is equal to " << inches
<< " inches." << endl;
}
} while (select != 'Q');
}
catch (int errID)
{
cout << "Error: " << errID << endl;
cout << "Please enter a positive number. ";
}
return 0;
}
解决方案
它应该是这样的:(我添加了一个标志bool bNeg = false
,if (inches>=0)
并且if (centimeters>=0)
在输入之后&如果输入对于“E”或“M”设置为负bNeg = true
)
bool bNeg = false;
if (select == 'E')
{
cout << "Enter the number of inches: ";
cin >> inches;
if (inches>=0) { // No meaning to negative values
centimeters = inches * 2.54;
cout << inches << " inches is equal to " << centimeters
<< " centimeters." << endl;
}
else bNeg = true;
}
else if (select == 'M')
{
cout << "Enter the number of centimeters: ";
cin >> centimeters;
if (centimeters>=0) { // No meaning to negative values
inches = centimeters / 2.54;
cout << centimeters << " Centimeters is equal to " << inches
<< " inches." << endl;
}
else bNeg = true;
}
if (bNeg) {
// tbd: say what you want to say
}
推荐阅读
- python - 在 PDFKIT python pdf 生成器工具中传递 Kerberos 凭据
- c# - 解析值时遇到意外字符:<。路径'',第 0 行,位置 0。' 在 C# 中 - 一个 GraphQL 客户端
- flutter - 是否可以在 Flutter 中导出 SVG
- python - 如何重用基于 DRF 类的视图 POST 方法?
- excel - 通过使用类接口或使用 Variant 变量来引用类模块?
- javascript - android chrome上的HTML5音频,除非调用alert(),否则不会播放
- java - Spring 集成邮件在获取电子邮件后设置标志“已标记”。有没有办法阻止它这样做?
- maven - 在另一个目录中为“uses”运行 github 操作
- c# - 如何在 ASP.NET 应用程序中分离并使用 SQL Server 数据库文件?
- python - pandas:仅当另一列中的值匹配时才计算行之间的重叠单词