简体   繁体   English

两个正整数相加得到否定答案。为什么?

[英]Adding two positive integers gives negative answer.Why?

#include<iostream>

using namespace std;

int main(){

  int x = 1967513926;
  int y = 1540383426;

  cout<<x+y;

return 0;
}

Sum of above two integers is 3507897352 < 2^32.So Why wrong answer?以上两个整数之和为 3507897352 < 2^32.So 为什么答案错误? Please help...请帮忙...

int是有符号类型,所以它的最大值是 2^31 - 1 = 2147483647,而不是 2^32 - 1。所以在这种情况下你确实会溢出。

The behaviour of your program is undefined as you are overflowing the int type:当您溢出int类型时,程序的行为未定义:

Paragraph 5/4 of the C++11 Standard (regarding any expression in general): C++11 标准的第 5/4 段(关于任何一般表达式):

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behaviour is undefined.如果在对表达式求值期间,结果未在数学上定义或不在其类型的可表示值范围内,则行为未定义。 [...] [...]

Check the limits of your arguments ( std::numeric_limits is useful here), before attempting a sum.在尝试求和之前,请检查参数的限制( std::numeric_limits在这里很有用)。

Alternatively, you can use unsigned types: overflowing those is safe as the standard states they will wrap around to 0 once the largest value is reached.或者,您可以使用unsigned类型:溢出这些是安全的,因为标准规定一旦达到最大值,它们将环绕为 0。

The limit of an int is 2.147.483.647 int的限制是 2.147.483.647

You're just overflowing it.你只是溢出它。

When you do (on an int ) 2.147.483.647 + 1. This gives you –2147483648.当你(在int )2.147.483.647 + 1 时。这给你 –2147483648。 ;) ;)

Deepak,迪帕克,

Please check the maximum limit which int provides, if your sum is going above it this will not work, you have to increase the length of your integer values.请检查 int 提供的最大限制,如果您的总和超过它,这将不起作用,您必须增加整数值的长度。

you can try numeric_limits which can bring you the max size you are looking for.您可以尝试 numeric_limits ,它可以为您带来您正在寻找的最大尺寸。

Hope this helps!!希望这可以帮助!!

Cheers!!干杯!!

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

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