【问题标题】:Basic menu driven program C++, infinite loop基本菜单驱动程序C++,无限循环
【发布时间】:2016-12-07 09:22:29
【问题描述】:

我一直在创建一个简单的菜单驱动转换程序,但不知何故在其中一个功能(英里到公里)中创建了一个无限循环,并且不知道如何修复它。

第二个功能似乎工作得很好。 非常感谢任何建议或提示。

#include <iostream>
#include <cmath>

using namespace std;

void showChoices();
double miles(double, double);
double degf(double, double);

int main ()
{
    double x, y;
    int choice;
    do
    {
        showChoices();
        cin >> choice;
        switch (choice)
        {
            case 1:
                cout << "Input miles to be converted, enter * to submit: \n";
                cin >> x >> y;
                cout << x << " is " << miles(x,y) << " in kilometers" << endl;
                break;
            case 2:
                cout << "Input degrees (in Farenheit) to be converted, enter * to submit: \n";
                cin >> x >> y;
                cout << x << " is " << degf(x,y) << " in degrees Celsius" << endl;
                break;
        }
    }
    while (choice != 2);
    return 0;
}
void showChoices()
{
    cout << "MENU" << endl;
    cout << "1: Miles to Kilometers " << endl;
    cout << "2: Farenheit to Celsius " << endl;
}
double miles(double mi, double km)
{
    return km = mi * 1.609344;
}
double degf(double fah, double cel)
{
    return cel = 5*(fah-32)/9;
}

【问题讨论】:

  • 既然已经发现了这个bug,我建议你有“默认”的情况,可能你可以添加一个字段来检查你是否想继续,更好的方法控制你的循环。

标签: c++ infinite-loop


【解决方案1】:

For 选择是 1:while 循环始终为真,因此它进入循环。

将选项添加为 3:退出。 将 while 条件更改为 (choice != 3),这将打破循环。

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多