c++ - 程序运行时数组总和给出错误答案

标签 c++

程序运行顺利,编译时我没有任何错误或警告,就在它获得最终结果时,无论我输入什么,我只会得到一堆随机字母和数字。

代码如下:

#include <iostream>
#include <string>

using namespace std;

int main()
{
     int hold;
     int n;
     int * result = new int;
     int * price = new int;
     std::string items[6];

        for (n=0; n<6; n++)
        {
            cout << "Item#" << n+1 << ": ";
            cin >> items[n];
        }
        cout <<  "\nYou Entered: ";
        for (int n=0; n<6; n++)
            cout << items[n] << ", ";

    for (n=0; n<6; n++)
    {
        if (items[n] == "ab"){
        price[n] = 2650;
        }

        else if (items[n] == "ae"){
        price[n] = 1925;
        }

        else if (items[n] == "ie"){
        price[n] = 3850;
        }

        else if (items[n] == "bt"){
        price[n] = 3000;
        }

        else if (items[n] == "pd"){
        price[n] = 2850;
        }

        else if (items[n] == "ga"){
        price[n] = 2600;
        }

    }

    for (n=0; n<6; n++)
    {
     result += price[n];
    }

    cout << "\nTotal gold for this build: " << result;
    cin >> hold;
    return 0;
}

最佳答案

int * price = new int;

int * result = new int;

分别分配一个int。您的意思可能是 new int[6]

但话又说回来,您应该改用 std::vector

我真的很失望你没有听取 - https://stackoverflow.com/a/12868164/673730 的建议- 如果你有,你现在不会有这个问题。这不是一个好的学习方式。

关于c++ - 程序运行时数组总和给出错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12874399/

相关文章:

c++ - c++中的位运算

c++ - "Bitwise And"和 C++ 中的左填充

c++ - 使用最少的代码行读取 C++ 中的表格数字数据

c++ - 多类编译错误

c++ - 为什么在 C++ 类中的成员变量上使用前缀

c++ - 在类中初始化 const

C++ + OpenCV = 访问冲突读取位置 0x02176000

c++ - 使用模板按内部数据对对象进行排序的排序算法

c++ - 读取以 bigendian 编写的文件

c++ - 命名空间中定义的变量或函数何时分配内存?