gpt4 book ai didi

c++ - 查找点积的函数

转载 作者:行者123 更新时间:2023-11-30 05:04:38 25 4
gpt4 key购买 nike

我正在尝试填充两个数组,然后使用一个函数来查找点积。有时它会起作用,有时它不会。我不确定这是我填充数组的方式,还是我处理函数的方式。此外,如果我将大小设置为 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;
}

最佳答案

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]{};

关于c++ - 查找点积的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com