【发布时间】:2021-11-20 10:15:56
【问题描述】:
该程序没有错误,但每次我运行该程序时,尽管“数量”和“成本”具有值,但总结果为 0。如何以某种方式编写此代码,以便 total 实际输出通过数量和成本相乘计算得出的数字?
{
char itemAnswer = 'a';
double qty = 0;
double cost = 0;
double total = qty*cost;
double payment = 0;
double change = payment-total;
std::cout << "Which item would you like to buy?" << std::endl;
std::cout << "a. Notebook | b. Pencil | c. Ballpen" << std::endl;
std::cin >> itemAnswer;
if(itemAnswer == 'a' || itemAnswer == 'A')
{
double cost = 15.50;
std::cout << "You chose notebook" << std::endl;
std::cout << "Enter quantity: ";
std::cin >> qty;
std::cout << "You added " << qty << " of notebook/s into your cart." << std::endl;
std::cout << "Your total will be " << total << " Php" << std::endl;
std::cout << "Enter payment: ";
std::cin >> payment;
while (payment < qty * cost)
{
std::cout << "You did not pay enough money" << std::endl;
std::cout << "Enter money again: ";
std::cin >> payment;
}
if (payment >= qty * cost)
{
std::cout << "You paid " << payment << " Php" << std::endl;
std::cout << "Your change is " << payment - qty * cost << " Php" << std::endl;
} ````
【问题讨论】:
-
double total = qty*cost;进行计算,当您修改qty或cost时,total之后不会改变 -
auto total = [&]() { return qty * cost; };和total()的使用可能会解决您的问题。不确定这是初学者的方式。
标签: c++ variables output logic