【问题标题】:While Loop In C++C++中的while循环
【发布时间】:2022-01-21 21:39:56
【问题描述】:

我想要关于下面代码的帮助,我想添加一个 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";
    }

【问题讨论】:

  • 然后添加循环。你有什么问题?
  • 这就是我要问的兄弟,在哪里放一个循环,你能演示一下吗?
  • 嘿,我推荐using cout;using cin; 而不是using namespace std;,因为这包括标准命名空间中的每个函数/类,这可能会产生命名冲突。
  • 对于您的下一个问题,我建议您阅读How to ask a good question
  • 不要对常规文本使用标题大小写(所有单词大写)。这样的文字读起来很烦人。

标签: c++ for-loop if-statement while-loop


【解决方案1】:

这是答案,您应该提示输入,然后使用 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;
}

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 2013-02-22
    • 1970-01-01
    • 2015-06-29
    • 2012-07-18
    • 2017-11-14
    • 1970-01-01
    • 2014-11-02
    • 2013-02-08
    相关资源
    最近更新 更多