我事先表示歉意,因为我找不到我要提出的问题的更好用词,所以我不妨在这里解释一下。我最近得到了《 C++ How to program》第9版书,我一直在练习,我正处于第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。仅使用总计即可完成工作。 lastTotal从未分配或更改!

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

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

总体还可以。但您显示的是lastTotal。

对于错误,将代码修改如下:
int main()
{
    ....

    return 0;
}

主要必须是int!

09-06 00:00