【问题标题】:Doing while loop properly until "0" input to stop the loop?正确执行while循环直到输入“0”以停止循环?
【发布时间】:2020-09-02 00:19:00
【问题描述】:

我需要帮助。我目前正在学习 C++ 编程,但仍处于初级水平。我仍在研究如何使 while 循环正常工作。我的想法是在插入正确的 code 输入时,switch 语句选择正确的 case 语句并循环返回以插入另一个输入,直到插入 0 以停止循环并计算main() 构造函数中的最终输出。

我知道我很快就会解决一些问题,但我仍在努力找出这个特定的部分。

#include <stdio.h>
#include <iostream>
#include <iomanip>

using namespace std;

double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;

void item001(){
    name = "Rice (5kg)";
    price = 11.5;
    discount = 0;
}

void item002(){
    name = "Rice (10kg)";
    price = 25.9;
    discount = 0;
}

void item003(){
    name = "Sugar (1kg)";
    price = 2.95;
    discount = 0;
}

void item_cal(){
    cout << "Please enter the quantity of the item: ";
    cin >> quantity;
    newPrice = (price + (discount * price)) * quantity;
    cout << "\nItem: " << name << "  ||  Quantity: " << quantity << "  ||  Price: RM" << newPrice << endl;
}

void input(){

    cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";

    while (code != 0){
        cin >> code;
        switch (code){
            case 001:
                item001();
                item_cal();
                break;

            case 002:
                item002();
                item_cal();
                break;

            case 003:
                item003();
                item_cal();
                break;

            default:
                cout << "\nWrong code" << endl;;
                break;

        total += newPrice;

        }
    }
}


int main(){
    input();
    totalSST = total * sst;
    grandTotal = total + totalSST;

    cout << fixed << setprecision(2);
    cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
    return 0;
}

【问题讨论】:

  • 另外,如果您有建议让我的代码看起来更好或工作得更好,那就太好了。
  • 试一试`while (cin >> code; && code != 0)`。用英文写着“虽然我们可以成功读入代码并且代码不为零,但处理代码中的值。”在尝试使用之前,请务必阅读一些内容。
  • 建议:全局变量死亡!在尽可能窄的范围内定义每个变量,并且更喜欢将变量传递给函数而不是扩大范围。全局变量破坏程序的方式比我想象的要多。

标签: c++ while-loop


【解决方案1】:

我在您的代码中看到的唯一功能问题是代码变量有可能初始化为 0(取决于编译器/随机性)。如果发生这种情况,您的输入法将在进入循环之前返回。除此之外,它看起来会起作用。当然,编程不仅仅是“让它工作”的艺术,风格和可读性也很重要。通常,您希望将变量限制在引用它们的最小范围内。 'code' 不应该是一个全局变量,它应该存在于输入法中。至于循环,有几种实现方式:可以使用“while(true)”循环,在这种情况下,可以在循环内部定义变量;另一方面,“do while”将保证一个循环运行(也许这很适合这里),但变量必须位于循环之外,至少在条件检查的范围内。您选择的方式通常是风格问题。下面,我使用了“while(true)”。

在编程中,可读性很重要(很多)。我认为如果将数据分解成几个结构,比如“Bill”和“Food”,这个程序会更容易阅读。要考虑的另一件事是如何在不引入显着复杂性的情况下扩大程序的使用范围。例如,它可以适用于任何杂货店(任何一组食品/价格)。这通常是确定一组适当的参数来提供程序的问题。 要执行这些操作,您可以编写如下内容:

#pragma once
#include <string>
#include <map>

using namespace std;

namespace market {
    const double& sst = 0.06;

    struct Bill {
        double total = 0;
        double totalSST = 0;
        double grandTotal = 0;
    };

    struct Food {
        const char* name;
        double price;
        double discount;

        Food(const char* name, double price, double discount = 0)
            : name(name), price(price), discount(discount) {}

        double result_price() const {
            return price - price * discount;
        }
    };

    struct GroceryStore {
        const char* name;
        std::map<int, Food> inventory;
        GroceryStore(const char* name, std::map<int, Food> inventory)
            : name(name), inventory(inventory) { }
    };

    void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
        // check error conditions
        if (store.inventory.find(exit_code) != store.inventory.end()) {
            // that's the 'exit_code' code silly!
            cout << "Bad store.  Come back another time." << endl;
            return;
        }
        cout << "Welcome to " << store.name << endl;
        if (show_menu) {
            cout << "The following items are available for purchase:" << endl;
            for (auto p : store.inventory) {
                cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
            }
        }
        cout << "Enter the product code of the item you wish to purchase:";
        int code;
        cin >> code;
        while (true) {
            auto food_it = store.inventory.find(code);
            if (food_it == store.inventory.end()) {
                cout << "Thanks for stopping by." << endl;;
                break;
            }
            cout << "Please enter the quantity of the item: ";
            uint32_t quantity;
            cin >> quantity;
            auto& food = food_it->second;
            auto disc_price = food.price - (food.discount * food.price);
            bill.total += disc_price * quantity;
            cout << "\nItem: " << food.name << "  ||  Quantity: " << quantity << "  ||  Price: RM" << disc_price << endl;
            cout << "Would you like anything else?  Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
            cin >> code;
        }
    }

    void ring_up(Bill& bill) {
        bill.totalSST = bill.total * sst;
        bill.grandTotal = bill.total + bill.totalSST;
    }

    void run() {
        int code = 1;
        GroceryStore store("SMart", {
            { code++, Food("Rice (5kg)", 11.5, 0) },
            { code++, Food("Rice (10kg)", 25.9) },
            { code, Food("Sugar (1kg)", 2.95, 0) }
        });
        Bill bill;
        shop(store, bill, true);
        ring_up(bill);
        cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
    }
}

【讨论】:

    【解决方案2】:

    首先,当你输入 0 时,输入中有一个错误,然后它也不会中断 while 循环,因为检查的代码包含以前的值。 例如: 输入是 3 0 但是根据您的代码,当代码第二次运行并且检查条件时代码仍然包含 3 作为值并且代码将再运行一次

    【讨论】:

      【解决方案3】:

      尝试将代码初始化为某个值,例如 -1。我不太确定,但我认为对于全局 int 变量,它们将 int 变量初始化为 0。所以你的第一个循环不会运行。或者另一种方法是使用 do while 循环而不是 while 循环。

      do {
          cin >> code;
          switch (code){
              case 001:
                  item001();
                  item_cal();
                  break;
      
              case 002:
                  item002();
                  item_cal();
                  break;
      
              case 003:
                  item003();
                  item_cal();
                  break;
      
              default:
                  cout << "\nWrong code" << endl;;
                  break;
      
          total += newPrice;
      
          } while (code != 0);
      }
      

      这确保循环将至少运行一次,从而使代码初始化。 希望对你有帮助!玩得开心编程!

      【讨论】:

      • 我才编程一年,还在学习中,如有错误,请高人指正。
      • 不幸的是,这将 0(有效输入)归类为“错误代码”。如果输入为零,则循环应立即退出,而不是在处理完零之后。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2017-06-20
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      相关资源
      最近更新 更多