简体   繁体   English

嵌套 if else 语句 C++

[英]nested if else statement C++

Although I have a statement that will exit the program if the user enters q or enters an invalid statement, the code after the if and if else statement still displays.虽然我有一个语句,如果用户输入 q 或输入无效语句,将退出程序,但 if 和 if else 语句之后的代码仍然显示。 For example, if the user enters q, the code compiles and reads: "You have chosen to exit the program. Thank you for using the program!"例如,如果用户输入 q,则代码编译并显示:“您已选择退出程序。感谢您使用该程序!” But then it also displays the weight and travel time as 0.但随后它也将重量和旅行时间显示为 0。

int main()
{
    string planet;
    char selection;
    double weightEarth = 0;
    double rate = 0;
    double distanceFromSun = 0;
    double surfaceGravity = 0;
    double newWeight = 0;
    double travelTime = 0;
    double travelDistance = 0;
    double distanceFromPlanets = 0;
    double distanceFromEarthToSun = 93.0;

    cout << "INTERPLANETARY TRAVEL MENU\n"
        << "----------------------------\n"
        << "a) Mercury\n"
        << "b) Venus\n"
        << "c) Earth\n"
        << "d) Mars\n"
        << "e) Jupiter\n"
        << "f) Saturn\n"
        << "g) Uranus\n"
        << "h) Neptune\n"
        << "q) Quit\n"
        << "Select a planet to travel to or q to quit the program :\n";

    cin >> selection;

    if (selection <= 'h')
    {

        cout << "Please enter your weight: \n";
        cin >> weightEarth;

        cout << "At what speed would you like to travel at?\n";
        cin >> rate;


        if (selection == 'a')
        {
            planet = "Mercury";
            surfaceGravity = 0.27;
            distanceFromSun = 36;
        }

        else if (selection == 'b')
        {
            planet = "Venus";
            surfaceGravity = 0.86;
            distanceFromSun = 67.0;
        }

        else if (selection == 'c')
        {
            planet = "Earth";
            surfaceGravity = 1.00;
            distanceFromSun = 93.0;
        }

        else if (selection == 'd')
        {
            planet = "Mars";
            surfaceGravity = 0.37;
            distanceFromSun = 141.0;
        }

        else if (selection == 'e')
        {
            planet = "Jupiter";
            surfaceGravity = 2.64;
            distanceFromSun = 483.0;
        }

        else if (selection == 'f')
        {
            planet = "Saturn";
            surfaceGravity = 1.17;
            distanceFromSun = 886.0;
        }

        else if (selection == 'g')
        {
            planet = "Uranus";
            surfaceGravity = 0.92;
            distanceFromSun = 1782.0;
        }

        else
        {
            planet = "Neptune";
            surfaceGravity = 1.44;
            distanceFromSun = 2793.0;
        }

    }

    else if (selection == 'q')
    {
        cout << "You have chosen to quit the program. Thank you for using the program!\n";
    }

    else
    {
        cout << "You have entered an invalid selection.\n";
    }

    newWeight = weightEarth * surfaceGravity;

    distanceFromPlanets = abs(distanceFromSun - distanceFromEarthToSun);

    travelTime = travelDistance / rate;

    cout << "Your weight on " << planet << " :  " << newWeight << endl;
    cout << "Your travel time to " << planet << ":\n";

Your q and invalid selection paths only print to the console, they don't exit the program.您的qinvalid选择路径仅打印到控制台,它们不会退出程序。 You would need a return 0;您需要return 0; in each.每个。

A better way, though, is to use a boolean that is set if you want to quit or the selection is invalid.不过,更好的方法是使用一个布尔值,如果您想退出或选择无效,则该布尔值已设置。

Here is one way to go about it.这是一种解决方法。

Declare the boolean as true将布尔值声明为真

bool validPlanet = true;

In the quit and invalid paths put this statementquitinvalid路径中放置此语句

validPlanet = false;

Then wrap your weight calculations in an if condition like so然后将您的重量计算包装在这样的if条件中

if( validPlanet)
{
    newWeight = weightEarth * surfaceGravity;

    distanceFromPlanets = abs(distanceFromSun - distanceFromEarthToSun);

    travelTime = travelDistance / rate;

    cout << "Your weight on " << planet << " :  " << newWeight << endl;
    cout << "Your travel time to " << planet << ":\n";

}

I'm assuming you have a return 0;我假设你有一个return 0; immediately after this, otherwise you'll need to use the validPlanet to assure those statements get called appropriately.在此之后立即,否则您将需要使用validPlanet来确保正确调用这些语句。

A simple way is to put getch() after the statement followed by exit(0);一个简单的方法是在语句之​​后加上getch()exit(0);

The last else if part then becomes:最后的 else if 部分则变为:

  else if (selection == 'q')
    {
        cout << "You have chosen to quit the program. Thank you for using the program!\n";
        getch();  //stops the current screen until a key stroke
        exit(0);  //exits the program. (zero value in the argument tells that it was a safe exit)
    }

OR, if you don't want the user to give a key stroke before exiting, you may use the delay(time) function which stops screen for a particular time.或者,如果您不希望用户在退出前敲击键盘,您可以使用delay(time)功能来停止屏幕特定时间。

Then the code becomes:然后代码变成:

  else if (selection == 'q')
    {
        cout << "You have chosen to quit the program. Thank you for using the program!\n";
        delay(1000)  //stops the current screen for 1 second. (time in miliseconds, 1000ms = 1 second)
        exit(0);  //exits the program. (zero value in the argument tells that it was a safe exit)
    }

Your code reformatted according to your need (since we haven't gone over the usage of booleans in if statements. At the moment I'm trying to re-structure my if and if else statements to fix the problem, but I can't seem to get the correct combination.)您的代码根据您的需要重新格式化(因为我们还没有讨论 if 语句中布尔值的使用。目前我正在尝试重新构建 if 和 if else 语句以解决问题,但我不能似乎得到了正确的组合。)

    double weightEarth = 0; //made these variables global so that display_result()can access it.
    double rate = 0;
    double distanceFromSun = 0;
    double surfaceGravity = 0;
    double newWeight = 0;
    double travelTime = 0;
    double travelDistance = 0;
    double distanceFromPlanets = 0;
    double distanceFromEarthToSun = 93.0;

    void display_result()
    {
           newWeight = weightEarth * surfaceGravity;

           distanceFromPlanets = abs(distanceFromSun - distanceFromEarthToSun);

           travelTime = travelDistance / rate;

           cout << "Your weight on " << planet << " :  " << newWeight << endl;
           cout << "Your travel time to " << planet << ":\n";
    }

    int main()
    {
    string planet;
    char selection;
    
    cout << "INTERPLANETARY TRAVEL MENU\n"
        << "----------------------------\n"
        << "a) Mercury\n"
        << "b) Venus\n"
        << "c) Earth\n"
        << "d) Mars\n"
        << "e) Jupiter\n"
        << "f) Saturn\n"
        << "g) Uranus\n"
        << "h) Neptune\n"
        << "q) Quit\n"
        << "Select a planet to travel to or q to quit the program :\n";

    cin >> selection;

    if (selection <= 'h')
    {

        cout << "Please enter your weight: \n";
        cin >> weightEarth;

        cout << "At what speed would you like to travel at?\n";
        cin >> rate;


        if (selection == 'a')
        {
            planet = "Mercury";
            surfaceGravity = 0.27;
            distanceFromSun = 36;
        }

        else if (selection == 'b')
        {
            planet = "Venus";
            surfaceGravity = 0.86;
            distanceFromSun = 67.0;
        }

        else if (selection == 'c')
        {
            planet = "Earth";
            surfaceGravity = 1.00;
            distanceFromSun = 93.0;
        }

        else if (selection == 'd')
        {
            planet = "Mars";
            surfaceGravity = 0.37;
            distanceFromSun = 141.0;
        }

        else if (selection == 'e')
        {
            planet = "Jupiter";
            surfaceGravity = 2.64;
            distanceFromSun = 483.0;
        }

        else if (selection == 'f')
        {
            planet = "Saturn";
            surfaceGravity = 1.17;
            distanceFromSun = 886.0;
        }

        else if (selection == 'g')
        {
            planet = "Uranus";
            surfaceGravity = 0.92;
            distanceFromSun = 1782.0;
        }

        else
        {
            planet = "Neptune";
            surfaceGravity = 1.44;
            distanceFromSun = 2793.0;
        }

        display_result();

    }

    else if (selection == 'q')
    {
        cout << "You have chosen to quit the program. Thank you for using the program!\n";
    }

    else
    {
        cout << "You have entered an invalid selection.\n";
    }
}
    

I created a function display_result() and shifted the code which was running on exiting the if-else statements.我创建了一个函数display_result()并移动了退出 if-else 语句时运行的代码。 Now this is being called every time only when you try to calculate the weight and not when you are exiting the program.现在,只有在您尝试计算重量时才会调用它,而不是在退出程序时调用。 This solved the problem of program complexity and lengthiness of program.这解决了程序复杂性和程序冗长的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM