c++ - 如何在 switch 语句后将一个变量添加到另一个变量

标签 c++

我提前道歉,因为我找不到更好的措辞来描述我要问的问题,所以我不妨在这里解释一下。我最近拿到了《C++ How to program 9th edition》这本书,一直在练习,现在已经到第5章了。我的问题是,在我的代码中,我无法在 while 循环中将总计添加到另一个变量。基本上我每次都返回 0,我不知道我做错了什么。有谁愿意了解一下情况并向我解释下一次我可以做得更好吗?我的意思是代码本身运行良好,没有错误,但我只是在计算时遇到了问题!

#include <iostream>
#include <iomanip>

using namespace std;

void main()
{
    int selection = 0;
    float total = 0.0;
    float lastTotal = 0.0;
    float product1 = 2.98;
    float product2 = 4.50;
    float product3 = 9.98;
    float product4 = 4.49;
    float product5 = 6.87;
    bool loop = true;

    while (loop == true)
    {
        cout << "Please make a selection from the following items and when you are done buying (-1) the products I will display your total\n" << endl;
        cout << "1: $" << product1 << endl;
        cout << "2: $" << product2 << endl;
        cout << "3: $" << product3 << endl;
        cout << "4: $" << product4 << endl;
        cout << "5: $" << product5 << endl << endl;

        total += lastTotal;

        cin >> selection;
        cout << "\n";

        switch (selection)
        {

            case 1:
                cout << "You have selected Product 1 which costs $2.98\n" << endl;
                total = product1;
                break;

            case 2:
                cout << "You have selected Product 2 which costs $4.50\n" << endl;
                total = product2;
                break;

            case 3:
                cout << "You have selected Product 3 which costs $9.98\n" << endl;
                total = product3;
                break;

            case 4:
                cout << "You have selected Product 4 which costs $4.49\n" << endl;
                total = product4;
                break;

            case 5:
                cout << "You have selected Product 5 which costs $6.87\n" << endl;
                total = product5;
                break;

            case -1:
                cout << "Thank you. Your total is: " << lastTotal << endl;
                loop = false;
                break;

            default:
                cout << "Invalid selection" << endl;            
        }       
    }
}

错误:

prog.cpp:6:11: error: '::main' must return 'int'
 void main()
           ^

也作为旁注。警告的确切含义是什么?我没有看到它们使我的代码崩溃,但当我运行它时它们弹出时我很担心。

最佳答案

您不需要使用 lastTotal 和 total。只需使用 total 就可以完成这项工作。 lastTotal 从未分配或更改!

cout << "Thank you. Your total is: " << lastTotal << endl;

更改为:

cout << "Thank you. Your total is: " << total << endl;

总的来说很好。但你显示的是 lastTotal。

针对报错修改代码如下:

int main()
{
    ....

    return 0;
}

main 必须是 int!

关于c++ - 如何在 switch 语句后将一个变量添加到另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27997421/

相关文章:

C++将字符串精确地转换为 double

c++ - 如何正确初始化 std::set<std::string>?

c++ - 数组损坏其字符 C++

c++ - Eigen 矩阵 ros/cols 不正确

c++ - 屏幕录像机

c++ - Boost Log 初始化后设置 max_size

c++ - 2 组独立的单选按钮,采用相同的 WINAPI 形式(无 MFC)

c++ - 变量 "variable name"周围的堆栈已损坏 C++

c++ - 可执行参数c++

c++ - 在网络服务中调用 C++