【问题标题】:How do I make sure that the total prints a value and not just 0如何确保总打印一个值而不仅仅是 0
【发布时间】: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; 进行计算,当您修改 qtycost 时,total 之后不会改变
  • auto total = [&amp;]() { return qty * cost; };total() 的使用可能会解决您的问题。不确定这是初学者的方式。

标签: c++ variables output logic


【解决方案1】:

C++ 不进行符号计算,而是采用变量的当前值 - 即当您编写时

int a = 0;
int b = 0;
int c = a + b;

然后你为ab分配不同的值,例如

a = 1;
b = 3;

c 仍将保持其值 0,并且不会自动更新为 4,除非您在更改 ab 之后执行 c = a + b; 再次 (或你可以将最初的int c = a + b;移动到你实际需要c的值的地方,如果你反正不需要它的话)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多