英文:
(C++) Visual Studio gives different outputs as other compilers for simple array sum problem
问题
#include <iostream>
using namespace std;
long ar[10];
int arraySize;
long aVeryBigSum(long arr[]) {
long total = 0;
for (int x = 0; x < arraySize; x++) {
total += ar[x];
}
return total;
}
int main() {
cin >> arraySize;
for (int x = 0; x < arraySize; x++) {
cin >> ar[x];
}
cout << aVeryBigSum(ar);
return 0;
}
输入:
5
1000000001 1000000002 1000000003 1000000004 1000000005
Visual Studio 输出:
705032719
在线IDE输出(正确):
5000000015
在这种情况下,不同编译器给出不同答案可能与long
数据类型的大小有关。
英文:
Code:
#include <iostream>
using namespace std;
long ar[10];
int arraySize;
long aVeryBigSum(long arr[]) {
long total = 0;
for (int x = 0; x < arraySize; x++) {
total += ar[x];
}
return total;
}
int main() {
cin >> arraySize;
for (int x = 0; x < arraySize; x++) {
cin >> ar[x];
}
cout << aVeryBigSum(ar);
return 0;
}
Input:
5
1000000001 1000000002 1000000003 1000000004 1000000005
Visual Studio output:
705032719
Online IED output(correct):
5000000015
I have no idea what to try in this situation as different compilers are giving me different answer. Assuming its something to do with data type long
答案1
得分: 5
你的 long int
可能是一个有符号的 32 位整数类型,这意味着它能够存储的最大正整数是 2,147,483,647,但你的求和结果为 5,000,000,015,因此发生了整数溢出。
将 long int
类型替换为 long long int
。或者为了使类型的大小更明确,包含 <cstdint>
并使用 int64_t
。
英文:
Your long int
is likely a signed 32-bit integer type, which means the largest positive integer it can store is 2,147,483,647, but your sum adds up to 5,000,000,015. Because this is larger, integer overflow has occurred.
Replace the long int
type with long long int
. Or to make the sizes of the types more explicit, include <cstdint>
and use int64_t
.
答案2
得分: 1
但是 "long" 的限制是 -2,147,483,648 到 2,147,483,647;你可以使用 std::numeric_limits<long>::max();
来获取限制。自第三次加法以来,总值已超出其限制,因此结果不如您的期望。将 "long" 更改为 "long long",您将获得正确的答案。
long long aVeryBigSum(long arr[]) {
long long total = 0;
for (int x = 0; x < arraySize; x++) {
total += arr[x];
}
return total;
}
至于其他集成开发环境(IDEs),也许它们进行了一些优化?
英文:
but the limits of the "long" is -2,147,483,648~2,147,483,647;
you can usestd::numeric_limits<long>::max();
to get the limit.
the value total has exceeded its limits since the third addition,so the outcome was not as your expectation.
change the long to "long long" you'll get the correct answer.
long long aVeryBigSum(long arr[]) {
long long total = 0;
for (int x = 0; x < arraySize; x++) {
total += ar[x];
}
return total;
}
as to other IDEs, maybe they do some optimization?
答案3
得分: 1
这个问题与特定的编译器和机器有关。C++标准只承诺int的长度不会比short更短,long的长度不会比int更短,long long的长度不会比long更短。
英文:
this problem is associated with specifical compilers and machines. c++ standard just promises that the length of int is not shorter than short, the length of long is not shorter than int, the length of long long is not shorter than long.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论