2个数组中最大元素的乘积

问题描述 投票:0回答:1

我正在尝试从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;
}
c++ arrays dynamic-memory-allocation
1个回答
0
投票

您在第二个if中有一个错误:max2 = arr1[j];应该为max2 = arr2[j];

但是,正如其他人指出的那样,有更好的方法来解决此问题。最重要的是,您可以按照WhozCraig的建议检查最大阅读时

作为通常对您有用的补充说明,您可以在同一行中声明和初始化变量,如下所示:

int max1 = 0;

代替

int max1;
max1 = 0;
© www.soinside.com 2019 - 2024. All rights reserved.