Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - 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? Please help...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An int is a signed type, so its maximum is 2^31 - 1 = 2147483647, not 2^32 - 1. So you do get an overflow in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...