首页 > 解决方案 > 我倒数第二个值是垃圾,程序是关于计算总和

问题描述

#include <iostream>
using namespace std;

int main()
{
    int oldsize;

        string choice;
        cout << "Welcome to the Walmart Calculation Center!";
        cout << endl;
        cout << "Enter the Number of Items" << endl;
        cin >> oldsize;
        int* items = new int[oldsize];
        for (int i = 0; i < oldsize; i++)
        {
            cout << "ENTER THE PRICE OF ITEM" << i + 1 << "!" << endl;
            cin >> items[i];
        }
           cout << "Do you want to add more items? (YES OR NO)" << endl;
           cin >> choice;
        if (choice == "YES")
        {
            int newbie;
            int newsize;


            int total = 0;
            while (choice == "YES")
            {
                newsize = oldsize + 1;
                int* Nitems = new int[newsize];

                for (int i = 0; i < oldsize; i++)
                {
                    Nitems[i] = items[i];
                }
                cout << "Enter the Price of New ITEM!" << endl;
                cin >> newbie;
                Nitems[oldsize] = newbie;
                oldsize = newsize;
                cout << "Do you want to add more items? (YES OR NO)" << endl;
                cin >> choice;
                if (choice=="NO")
                {
                    for (int i = 0; i < newsize; i++)
                    {
                        cout << Nitems[i] << endl;
                    }
                }
            }

        }

    }

这个程序是关于在商店计算账单的总和。并询问用户是否要输入任何其他项目,直到他/她说不。最后它显示总账单。

标签: c++arraysloopsvisual-c++dynamic

解决方案


你永远不会改变items数组,但你会改变oldsize代表它的大小的变量。当您尝试从 to 复制项目itemsNitems,您会超出items数组的范围(因为oldsize大于数组的实际大小)。

最简单的解决方法是在更改大小的同时重新items指向。Nitems

while (choice == "YES")
{
    newsize = oldsize + 1;
    int* Nitems = new int[newsize];

    for (int i = 0; i < oldsize; i++)
    {
        Nitems[i] = items[i];
    }

    cout << "Enter the Price of New ITEM!" << endl;
    cin >> newbie;
    Nitems[oldsize] = newbie;

    oldsize = newsize;
    items = Nitems; //here

    cout << "Do you want to add more items? (YES OR NO)" << endl;
    cin >> choice;
    if (choice=="NO")
    {
        for (int i = 0; i < newsize; i++)
        {
            cout << Nitems[i] << endl;
        }
    }
}

看到标有注释的行了吗?它使items指针指向与 相同的数组Nitems。不涉及复制,如果您更改items[1]Nitems[1]将看到相同的更改。但是有两个指向同一个数组的指针可以让您在下一次迭代中创建新数组时保留当前数组。


内存泄漏当然存在问题,但在您学会如何正确管理内存之前不要太担心。放置不当delete比内存泄漏更糟糕(尤其是在这样的小程序中)。


当然,如果您使用以下代码,您的代码会简单得多std::vector

std::vector<int> items;
while (choice == "YES")
{
    cout << "Enter the Price of New ITEM!" << endl;
    cin >> newbie;
    items.push_back(newbie);

    cout << "Do you want to add more items? (YES OR NO)" << endl;
    cin >> choice;
    if (choice=="NO")
    {
        for (int i = 0; i < items.size(); i++)
        {
            cout << items[i] << endl;
        }
    }
}

推荐阅读