【发布时间】: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