简体   繁体   English

无法使用 for 循环对整数向量求和 c++

[英]Can't sum a vector of integers using for loop c++

I am writing a function that takes a vector of integers as input, and iterates through the vector to obtain the maximum and minimum values in the vector, as well as the sum.我正在编写一个 function,它将一个整数向量作为输入,并遍历该向量以获得向量中的最大值和最小值,以及总和。 The maximum possible integer in the argument vector is 1000000000.参数向量中最大可能的 integer 是 1000000000。

void miniMaxSum(vector<long> arr) {
    long sum = 0;
    long min = 1000000000;
    long max = 0;
    for (int i = 0; i < arr.size(); i++) {
        cout << arr[i] << endl;
        sum += arr[i];
        if (arr[i] < min) {
            min = arr[i];
        }
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    cout << sum << endl;
}

Using the following input vector as argument:使用以下输入向量作为参数:

vector<long> x = {793810624,895642170,685903712,623789054,468592370 };

The sum is a negative number: -827229366总和为负数:-827229366

long is usually a 32-bit type on most operating systems (at least 32-bit). long在大多数操作系统(至少 32 位)上通常是 32 位类型。 So the maximum value it can hold is 2,147,483,647 .所以它可以容纳的最大值是2,147,483,647

The sum of your numbers is 3,467,737,930 .你的数字总和是3,467,737,930 So it overflows.所以它溢出了。

Consider using unsigned long or long long (at least 64 bits) or unsigned long long for larger numbers.考虑使用unsigned longlong long (至少 64 位)或unsigned long long用于更大的数字。 Or you could even use intmax_t or uintmax_t to get the biggest integer that is supported.或者您甚至可以使用intmax_tuintmax_t来获得支持的最大 integer。

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

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