C++ 在循环"if"内丢失赋值的变量

C++ Variables Losing Assignment Inside "if" Loop

本文关键字:赋值 变量 循环 if C++      更新时间:2023-10-16

所以我确信这是一个非常简单的问题,但我才刚刚开始。

在程序中,有一个简单的输入验证。如果输入正确,则没有问题。

问题是,当测试程序时出现错误,比如输入零或负数,输出中的所有变量都是空的(即字符串变为空,数字变为零(。

提前感谢您的帮助和洞察力。

// This menu driven program determines the time sound will take to travel through
// gas, liquid, and solid, given a distance from a user.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// constants
const double    AIR_SPEED_RATE_PER_SECOND_SOUND = 1100.0,       //in feet per second
                WATER_SPEED_RATE_PER_SECOND_SOUND = 4900.0,     // in feet per second
                STEEL_SPEED_RATE_PER_SECOND_SOUND = 16400.0;    // in feet per second
// Program defined variables
double          Time_To_Travel = 0.0;       // in seconds
string          Medium;
// User defined variables
double          distance_of_travel; //in feet
int             menu_selection;
//Display a menu for mediums of sound conduction.
cout << "Sound travels at different speeds through air, water, and steel." << endl;
cout << "nThis program will calculate the time it takes, in feet per second, for " 
"sound to travel a given distance." << endl;
cout << "Please select a number choice below:nn1. Airn2. Watern3. Steel " << endl;
//Get input from user.
cout << "nEnter Selection: ";
cin >> menu_selection;
cout << "nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;

// Input validate selection is on the menu
if (menu_selection >= 1 && menu_selection <= 3)
    {
    if (distance_of_travel > 0.0)  // input validation distance is positive
        {
        switch (menu_selection)  // calculate the time of travel based on user input
            {
            case 1: Medium = "air";
                    Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
                break;
            case 2: Medium = "water";
                    Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
                break;
            case 3: Medium = "steel";
                    Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
                break;
            }
        }
    else
        {
        cout << "nPlease enter a distance greater than zero: ";
        cin >> distance_of_travel;
        }
    }
else
    {
    cout << "nMenu selection is not 1, 2, or 3.nnPlease correctly enter a number 1 through 3: ";
    cin >> menu_selection;
    }
// Format to four decimal places and display the time sound takes to travel given distance.
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;

}

if语句是一个简单的分支,而不是循环。在if结束时,执行继续经过块的结束。

if (menu_selection >= 1 && menu_selection <= 3)

当为false时,这将跳过程序的核心,跳到处理无效输入的代码。

else
{
    cout << "nMenu selection is not 1, 2, or 3.nnPlease correctly enter a number 1 through 3: ";
    cin >> menu_selection;
}

再次输入menu_selection后,控制流向

cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;

从未对新输入进行操作,并且打印未经更改的值。用封装用户输入的do {...} while(condition);循环替换初始if。一旦输入令人满意,就可以进入程序的核心。

bool is_good;
do
{
    is_good = false;
    cout << "nEnter Selection: ";
    cin >> menu_selection;
    cout << "nEnter distance in feet the sound will travel: ";
    cin >> distance_of_travel;
    if (menu_selection < 1 || menu_selection > 3 || distance_of_travel < 0)
        cout << "error message here";
    else
        is_good = true;
} while (!is_good);

您可以通过将default块添加到switch语句来处理零、负数或未在case块中定义的所有可能输入。然后你的代码会像这样。

switch (menu_selection)  // calculate the time of travel based on user input
        {
        case 1: Medium = "air";
                Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
            break;
        case 2: Medium = "water";
                Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
            break;
        case 3: Medium = "steel";
                Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
            break;
        default:
            // handle zero, negative numbers and so on.
            break;
        }

参考:http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm