简体   繁体   English

为什么我的 C++ 最大化成对乘积代码不起作用?

[英]Why isn't my C++ maximizing pairwise product code working?

So the problem asked me to find the greatest product from a given sequence of non-negative integers.所以问题要求我从给定的非负整数序列中找到最大的乘积。 What I did was I tried to find the greatest two integers from the sequence (for which I used a vector, by taking an input of n numbers) and multiplied them, since there are no negative integers.我所做的是尝试从序列中找到最大的两个整数(为此我使用了一个向量,通过输入 n 个数字)并将它们相乘,因为没有负整数。 I used the long long type as well, since just an int type would not be enough for huge numbers.我也使用了 long long 类型,因为仅 int 类型不足以处理大量数据。 I kept getting a random huge number as the output whenever I tried to run the program:每当我尝试运行该程序时,我都会得到一个随机的巨大数字 output:

#include <iostream>
#include <vector>
using namespace std;

long long max_prod(const vector<int>& numbers) {
    int max1 = -1;
    int max2 = -1;
    int n = numbers.size();
    for (int i = 0; i<n; i++){
        if (numbers[i] > numbers[max1]) 
            max1 = i;
    }
    for (int j = 0; j < n; j++) {
        if (numbers[j] > numbers[max2] && j!=max1)
            max2 = j;
    }
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}

int main(){
    int n;
    cin >> n;
    vector<int> numbers(n);
    for (int i = 0; i<n; i++){
        cin >> numbers[i];
    }
    long long result = max_prod(numbers);
    cout << result << "\n";
    return 0;
}

the last line is the output given by the program最后一行是程序给出的output

You haver undefined behavior right here你在这里有未定义的行为

long long max_prod(const vector<int>& numbers) {
    int max1 = -1; <<<<<====
    int max2 = -1;
    int n = numbers.size();
    for (int i = 0; i < n; i++) {
        if (numbers[i] > numbers[max1]) <<<<<==
            max1 = i;
    }
    for (int j = 0; j < n; j++) {
        if (numbers[j] > numbers[max2] && j != max1)
            max2 = j;
    }
    return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}

You try to access numbers[-1] (twice once in the j loop and once in the i loop).您尝试访问numbers[-1] (在 j 循环中两次,在 i 循环中一次)。

Set maxi and maxj to 0将 maxi 和 maxj 设置为 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM