繁体   English   中英

在 C++ 中循环

[英]While Loop In C++

伙计们,我需要关于下面代码的帮助,我想添加一个 While 循环,用户在其中不断获取 Else 语句的 Cout。 直到用户满足 If 或 Else-If 条件。 换句话说,程序应该只在用户写'g''G''b''B'时结束,否则它应该继续显示其他人的Cout,再次要求输入正确的值。

#include <iostream>
using namespace std;

int main()
{
    string item;
    float price;
    int quantity;
    float total;
    char experience;

    cout << "Write The Name Of Item You Want To Buy:" << endl;
    getline(cin, item);

    cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
    cin >> price;

    cout << "What Is The Quantity Of " << item << endl;
    cin >> quantity;

    total = price*quantity;

    cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;
    
    cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
    cin >> experience;

    if (experience == 'g' || experience == 'G')
    {
        cout << "We Appreciate Your Feedback THANKS For Shopping :)";
    }
    else if (experience == 'b' || experience == 'B')
    {
        cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
    }
    else
    {
        cout << "Write \"G\" If Good And \"B\" If Bad";
    }

这是答案,您应该提示输入,然后使用 while 循环而不是 IF-ELSE 检查输入,以确保用户提供了您想要的答案。 这实际上是一个简单的逻辑问题。 您也可以探索 do-while 循环。

#include <iostream>
using namespace std;

int main()
{
    string item;
    float price;
    int quantity;
    float total;
    char experience;

    cout << "Write The Name Of Item You Want To Buy:" << endl;
    getline(cin, item);

    cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
    cin >> price;

    cout << "What Is The Quantity Of " << item << endl;
    cin >> quantity;

    total = price*quantity;

    cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;

    cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
    cin >> experience;

    while (experience != 'G' && experience != 'g' && experience != 'B' && experience != 'b') {
        cout << "Write \"G\" If Good And \"B\" If Bad\n";
        cin >> experience;
    } 

    if (experience == 'g' || experience == 'G') {
        cout << "We Appreciate Your Feedback THANKS For Shopping :)";
    } else if (experience == 'b' || experience == 'B') {
        cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
    }

    return 0;
}

暂无
暂无

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

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