#Getting unexpected result from my code. Can't detect why?

27 messages · Page 1 of 1 (latest)

stable owl
#

Q: Two numbers will be given. I have to show the sum, sub and multi of them. Here is my code:
#include <stdio.h>

int main(){
int a, b;
long long int result1, result2, result3;

scanf("%d%d", &a, &b);

result1=a+b;
result2=a*b;
result3=a-b;

printf("%d + %d = %lld\n", a, b, result1);
printf("%d * %d = %lld\n", a, b, result2);
printf("%d - %d = %lld\n", a, b, result3);

return 0;

}

Expected result:
60642 + 92657 = 153299
60642 * 92657 = 5618905794
60642 - 92657 = -32015
Result I am getting:
60642 + 92657 = 153299
60642 * 92657 = 1323938498
60642 - 92657 = -32015
Can you explain why it's happening only with multiplication?

fair nimbusBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

cobalt apex
cobalt apex
#

use %lld for them all

stable owl
#

okay, let me try

cobalt apex
#

if it's gcc then -Wall -W -pedantic are some that you should use

stable owl
#

okay, I updated my code as you said. But, still showing the same result.

stable owl
cobalt apex
#

what does your code look liken ow

cobalt apex
#

i see

#

a and b are both ints so this is doing int multiplication and the result is larger than the maximum int value

#

you'll either have to store both a & b as long longs

#

or typecast a * b as long long

#

result2 = (long long) a * b;

stable owl
#

yeah, thanks. Typecast is working. But, if I change datatype of a&b to long long. Then not working.

#

Can you tell me why this is happening?

cobalt apex
#

but the scanf call still expects ints because of %d

#

change the %d to %li to store them as long long ints instead of ints

fair nimbusBOT
#

@stable owl Has your question been resolved? If so, run !solved :)

stable owl
#

wow, thank you so much for you great support.

#

!solved