Buqian Zheng
Buqian Zheng

Reputation: 341

Add two integers up and print the result, when i use `int` it's right but when i use `double` it's wrong?

Input two integers a and b, 1<=a,b<=10^6. Print their sum.

code using int:

int a, b;
cin >> a >> b;
cout << a + b;

code using double:

double a, b;
cin >> a >> b;
cout << a + b;

After I submit these code to the online judge website, the first code can pass all 5 cases, but the second can pass only 3 and the other 2 are wrong answer.

But since double include the range of int, why can't it pass some of the cases that int can? I understand using double instead of int may be a waste of memory, but I think this should not cause any mistake.

Besides, when using double, if I print the result using printf("%.0lf", a + b);,it can also pass all 5 cases.

I know this is an extremely simple program but i can't figure out why it may be wrong using double.

Upvotes: 3

Views: 112

Answers (1)

Buqian Zheng
Buqian Zheng

Reputation: 341

When the result is larger than or equal to 10^6, it would be printed by cout in scientific notation which is not accepted by the online judge.

Upvotes: 1

Related Questions