我正在尝试从2个动态分配的数组中获得最大非相等元素的乘积 (例如,如果数组1为:7,5,9,数组2为:8,9,1乘积应为9 * 8 = 72)。 但是结果对我来说永远都不准确,我开始调试但也无法找出问题所在
请在下面找到我的代码
#include <iostream>
using namespace std;
int main()
{
int size;
cin >> size;
int *arr1 = new int[size];
int *arr2 = new int[size];
int max1;
int max2;
max1 = 0;
max2 = 0;
for (int i = 0; i < size; i++)
{
cout << "Please enter the elements for first array" << endl;
cin >> arr1[i];
}
for (int k = 0; k < size; k++)
{
cout << "Please enter the elements for second array" << endl;
cin >> arr2[k];
}
for (int l = 0; l < size; l++)
{
if(arr1[l]>max1)
{
max1 = arr1[l];
}
}
for (int j = 0; j < size; j++)
{
if (arr2[j]>max2 && arr2[j]!=max1)
{
max2 = arr1[j];
}
}
int product;
product = max1*max2;
cout << "product is = " << product << endl;
delete []arr1;
delete []arr2;
}
答案 0 :(得分:1)
尝试中有几个错误:
if
中,行max2 = arr1[j];
应该是max2 = arr2[j];
; arr1
和arr2
具有相同的最大条目数,那么您就可以选择要放弃的一个最大值,以第二至最大进入。您的代码始终选择从arr1
中获取最大值;因此,例如,如果arr1
为[1, 2, 3]
,而arr2
为[0, 1, 3]
,则最终您将从3
和{{1}中选择arr1
}来自1
。但是,如果您从arr2
中获得了最大值,那么您将以arr2
中的2
和arr1
中的3
结尾:哪个更好?没有人可以说,因为这个问题无法做出选择。实际上,错误3(带有相关示例)仅表明问题的陈述(如果需要,则为请求)本身就是错误的。
作为通常对您有用的补充说明,您可以在同一行中声明和初始化变量,如下所示:
arr2
代替
int max1 = 0;
答案 1 :(得分:0)
对数组排序并比较最大的元素。如果它们相同,则返回一个最大元素和一个第二大元素的最大乘积:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int size;
cin >> size;
int *arr1 = new int[size];
int *arr2 = new int[size];
for (int i = 0; i < size; i++)
{
cout << "Please enter the elements for first array" << endl;
cin >> arr1[i];
}
for (int k = 0; k < size; k++)
{
cout << "Please enter the elements for second array" << endl;
cin >> arr2[k];
}
std::sort(arr1, arr1 + size);
std::sort(arr2, arr2 + size);
cout << "product is = ";
if (arr1[size-1] != arr2[size-1])
cout << arr1[size-1] * arr2[size-1] << endl;
else
cout << std::max(arr1[size-1] * arr2[size-2], arr1[size-2] * arr2[size-1]) << endl;
delete []arr1;
delete []arr2;
}
输入:
3
7 5 9
8 9 1
输出:
product is = 72
答案 2 :(得分:-1)
好的,您的代码中存在2个概念性问题:
1您假设您将获得至少一个正数,但要求并未说明。如果所有数字均为负数,您将得到错误的结果。
2寻找最大数是错误的,假设您有2个数组:[7,8,9]和[6,7,9]您将给出9 * 7而不是8 * 9。
这是正确的解决方案:
std::vector<int> v1( size ), v2( size );
// make sure that size >= 2 and enter data
std::nth_element( v1.begin(), v1.begin() + 1, v1.end(), std::greater<int>() );
std::nth_element( v2.begin(), v2.begin() + 1, v2.end(), std::greater<int>() );
int product = v1[0] * ( v1[0] == v2[0] ? std::max( v1[1], v2[1] ), v2[0] );