程序运行顺利,编译时我没有任何错误或警告,就在它获得最终结果时,无论我输入什么,我只会得到一堆随机字母和数字。
代码如下:
#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/