在switch语句之后,我究竟如何将变量添加到另一个变量

时间:2015-01-17 07:51:40

标签: c++

我提前道歉,因为我无法找到问题的更好的措辞,所以我不妨在这里解释一下。我最近得到了C ++如何编写第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()
           ^

另外作为旁注。这些警告究竟意味着什么?我没有看到它们使我的代码崩溃,但是当我运行它时它会弹出它时会引起我的注意。

3 个答案:

答案 0 :(得分:2)

要为总计添加值,请将总和分配给总计。

total = total+value

标准说主要功能应该返回int

int main()

答案 1 :(得分:2)

您不需要使用lastTotal和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!

答案 2 :(得分:1)

total = product1;

此行将总计设为product1。它不会将product1添加到总数中。

与往常一样,计算机完全按照您的要求执行操作,并使用total的值覆盖product1。产品2,3,4和5也会发生类似的情况。