我正在尝试填充两个数组,然后使用函数来查找点积。有时它会起作用,有时却不起作用。我不确定我是如何填充数组的,或者我是如何处理该功能的。另外,如果我将大小设置为6并输入1,2,3,4,5,6,则第一个数组将填充1,2,3,4,1,2 ...它将在4之后重置。数组已正确填充。 我不知道是否有人可以帮我解决这个问题。
#include <iostream>
using namespace std;
int dotProduct(int* array1, int*array2, int size);
int main() {
int size = 0;
int *array_one = new int[size]{};
int *array_two = new int[size]{};
cout << "Please enter array size:" << "\n";
cin >> size;
while (size <= 0) { // First while loop, checking array size
cout << "Please enter array size:" << "\n";
cin >> size;
} //end of first while loop
cout << "========= Begin Entering Array Elements ========="
<< "\n";
cout << "Array 1: "<< "\n";
for (int i = 0; i<size; i++){ // Filling up first array, first for
loop
cout << "Enter element number "<< i+1 << ": " ;
cin >> array_one[i];
} // end or first for loop
cout <<"=================================================" <<
"\n";
cout << "Array 2:" << "\n";
for (int i = 0; i<size; i++){ // Filling up first array, first for
loop
cout << "Enter element number "<< i+1 << ": " ;
cin >> array_two[i];
}
cout << "The dot product is: " <<
dotProduct(array_one,array_two,size);
}
int dotProduct(int *arrayUno, int *arrayDos, int size){
int total = 0;
for (int i =0; i <= size ; i++ ){
total = total + (*arrayUno)*(*arrayDos);
arrayUno++;
arrayDos++;
}
return total;
}
答案 0 :(得分:1)
int size = 0;
int *array_one = new int[size]{};
int *array_two = new int[size]{};
cout << "Please enter array size:" << "\n";
cin >> size;
while (size <= 0) { // First while loop, checking array size
cout << "Please enter array size:" << "\n";
cin >> size;
} //end of first while loop
在获得大小之前分配数组。你必须先获得尺寸。将此代码更改为:
int size = 0;
cout << "Please enter array size:" << "\n";
cin >> size;
int *array_one = new int[size]{};
int *array_two = new int[size]{};