在C ++中的If-else语句中感到困惑

时间:2016-09-19 23:36:06

标签: c++ if-statement

为一个项目工作,所有的代码工作除了一部分,我认为我可能搞砸了整个代码,可能需要重写(这就是为什么我在这里问)。程序会要求您从三个选项中选择一个,然后选择您想要的项目数量。但是,如果用户选择菜单上没有的内容,我们应该会显示错误消息。是否仍然可以在我的代码中获得一个有效的else语句?

cout << "Would you like a sandwich, a platter, or a salad? ";
cin >> choice;
if (choice == "sandwich")
{
    cout << "\n     How many sandwiches would you like? ";
    cin >> sandwich;
    if (sandwich >= 3)
    {
        cout << "\n     Each sandwich costs: $" << SANDWICH_DISCOUNT << endl;
        total = SANDWICH_DISCOUNT * sandwich;
        cout << "\n     The total cost of the sandwich(es) is: $" << total << endl<< endl;
    }
    else
    {
        cout << "\n     Each sandwich costs: $" << SANDWICH << endl;
        total = SANDWICH * sandwich;
        cout << "\n     The total cost of the sandwich(es) is: $" << total << endl<<endl;
    }
}

if (choice == "platter")
{
    cout << "\n     How many platters would you like? ";
    cin >> platter;
    if (platter >= 3)
    {
        cout << "\n     Each platter costs $" << PLATTER_DISCOUNT << endl;
        total = PLATTER_DISCOUNT * platter;
        cout << "\n     The total cost of the platter(s) is: $" << total << endl<<endl;
    }
    else
    {
        cout << "\n     Each platter costs $" << PLATTER << endl;
        total = PLATTER * platter;
        cout << "\n     The total cost of the platter(s) is: $" << total << endl<<endl;
    }
}
if (choice == "salad")
{
    cout << "\n     How many salads would you like? ";
    cin >> salad;
    if (salad >= 3)
    {
        cout << "\n     Each salad costs $" << SALAD_DISCOUNT << endl;
        total = SALAD_DISCOUNT * salad;
        cout << "\n     The total cost of the salad(s) is: $" << total << endl<<endl;
    }
    else
    {
        cout << "\n     Each salad costs $" << SALAD << endl;
        total = SALAD * salad;
        cout << "\n     The total cost of the salad(s) is: $" << total << endl<<endl;
    }
}

1 个答案:

答案 0 :(得分:7)

您只需在每个主要ifs之后添加一个else,例如:

System.arraycopy