首页 > 解决方案 > 变量可能未初始化/未初始化使用

问题描述

我正在用 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;

}

标签: c++try-catch

解决方案


它应该是这样的:(我添加了一个标志bool bNeg = falseif (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
    }

推荐阅读