正确地执行while循环,直到输入“ 0”才能停止循环?

时间:2020-05-16 03:54:00

标签: c++ while-loop

我需要帮助。我目前正在学习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;
}

3 个答案:

答案 0 :(得分:1)

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

在编程中,可读性很重要。我认为,如果将数据分解为几个结构,例如“账单”和“食物”,该程序将更易于阅读。要考虑的另一件事是如何扩展程序的使用范围,而又不会引起很大的复杂性。例如,它可以用于任何杂货店(任何食品/价格集)。通常,要确定一组适当的参数以供程序使用。 为此,您可以编写如下内容:

#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;
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试将代码初始化为某个值,例如-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);
}

这可以确保循环至少运行一次,从而初始化代码。 希望对您有帮助!祝您编程愉快!