{
// FIRST ARRAY
int NumberOfXValues;
double* FirstArray;
NumberOfXValues = 0;
FirstArray = new double[NumberOfXValues];
// END FIRST ARRAY
// SECOND ARRAY
int NumberOfProbabilities;
double* SecondArray;
NumberOfProbabilities = 0;
SecondArray = new double[NumberOfProbabilities];
// END SECOND ARRAY
// THIRD ARRAY
int Product;
double* ThirdArray;
Product = 0;
ThirdArray = new double[Product];
// END THIRD ARRAY
// OBTAINING THE NUMBER OF X VALUES
cout << "Please input the number of \"x\" values we will be using: ";
cin >> NumberOfXValues;
// END OF OBTAINING THE NUMBER OF X VALUES
// OBTAINING THE VALUES IN THE FIRST ARRAY
int x;
cout << "Please input the \"x\" values in order from least to greatest: " << endl;
cout << endl;
for (int x = 0; x < NumberOfXValues; x++)
{
cout << "Enter number: ";
cin >> FirstArray[x];
}
cout << endl;
// END OF OBTAINING THE VALUES IN THE FIRST ARRAY
// OBTAINING THE VALUES IN THE SECOND ARRAY
cout << "Please input the probabilities corresponding to their \"x\" values: " << endl;
cout << endl;
for (int x = 0; x < NumberOfXValues; x++)
{
cout << "Enter probability in decimal form: ";
cin >> SecondArray[x];
}
cout << endl;
// END OF OBTAINING THE VALUES IN THE SECOND ARRAY
// MULTIPLYING THE FIRST TWO ARRAYS TO OBTAIN THE THIRD
for (int x = 0; x < NumberOfXValues; x++)
{
ThirdArray[x] = FirstArray[x] * SecondArray[x];
}
// END OF MULTIPLYING THE FIRST TWO ARRAYS TO OBTAIN THE THIRD
//TEST
for (int x = 0; x < NumberOfXValues; x++)
{
cout << ThirdArray[x];
cout << endl;
}
//TEST
}
这是我第一次使用其中一个网站,但我已经工作了近一个多小时来解决这个问题。它运行完全平滑,直到它在第3个数组中显示第3个值。它总是给我一个奇怪的数字。
答案 0 :(得分:4)
问题是,在创建数组时,用于size的变量设置为0
:
int NumberOfXValues;
double* FirstArray;
NumberOfXValues = 0;
FirstArray = new double[NumberOfXValues];
此处FirstArray
为0
,因此会创建一个0
元素数组。
您必须在获取元素数量后创建数组。
cout << "Please input the number of \"x\" values we will be using: ";
cin >> NumberOfXValues;
FirstArray = new double[NumberOfXValues];
答案 1 :(得分:1)
当你说new Foo[NumItems]
时,该数组只会有NumItems
个项目,它不会自行增长。如果您想稍后调整大小,则需要分配正确大小的新数组并复制成员。有时您可以通过realloc
扩展当前的分配。
您的问题有两个方面:
对于第二种情况,您应该使用std::vector
,它会自动增长并为您省去麻烦。
std::vector<double> firstArray(initialSize);
firstArray.push_back(firstItem);
firstArray.push_back(secondItem);
//...
在目前的情况下,您可以推迟创建数组,直到您知道需要存储在其中的项目总数。