C++ 函数查找点积
我尝试填充两个数组,然后使用一个函数来查找点积。有时它会起作用,有时不会。我不确定是我如何填充数组,还是我如何处理函数。另外,如果我将大小设置为6并输入1,2,3,4,5,6,第一个数组将填充1,2,3,4,1,2。。。它在4点后复位。第二个数组已正确填充。 我不知道是否有人能帮我C++ 函数查找点积,c++,function,dynamic-memory-allocation,dot-product,C++,Function,Dynamic Memory Allocation,Dot Product,我尝试填充两个数组,然后使用一个函数来查找点积。有时它会起作用,有时不会。我不确定是我如何填充数组,还是我如何处理函数。另外,如果我将大小设置为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
#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;
}
#包括
使用名称空间std;
int点积(int*array1,int*array2,int-size);
int main(){
int size=0;
int*array_one=新的int[size]{};
int*array_two=新的int[size]{};
cout大小;
而(sizeint size=0;
int*array_one=新的int[size]{};
int*array_two=新的int[size]{};
cout大小;
虽然(size Now可能是一个非常好的时机。这是一个非常好的阅读!感谢分享!你应该在你的答案中添加while
循环。哦,天啊,我错过了那部分。谢谢。我的第一个错误是在函数中我没有初始化total。当我使total=0时,我不再有错误。现在数组位于错误的位置…我在看了几个小时的问题后,我甚至都没有意识到这一点。我感谢你的帮助!我真的很感谢。我需要学习如何调试我的小代码。这是一个小问题,我已经多次遇到过同样的情况。如果你认为这个答案有帮助,请随意接受它作为你问题的答案!
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]{};