Reputation: 1916
I have the following code that adds the input number. When i enter 12345, it gives me the correct result but when i enter 56789, it gives me wrong result.
Any help will be appreciated...
#include <stdio.h>
#include <conio.h>
main()
{
int d1, d2, d3, d4, d5, sum, number, n;
clrscr();
scanf("%d", &number);
printf("number=%d\n",number);
n=number;
d1=n % 10;
n=n / 10;
d2=n % 10;
n=n / 10;
d3=n% 10;
n=n / 10;
d4=n% 10;
n=n / 10;
d5=n;
sum=d1 + d2 + d3 + d4 + d5;
printf ("sum of digits =%d\n", sum);
getch();
}
Output result in picture..
Upvotes: 3
Views: 183
Reputation: 258568
You're probably overflowing the variables, try using long
instead of int
. For a 16-bit int
, the range is -32768
to 32767
. You can easily test this out by printing sizeof(int)
, which will probably be 2
(16 bits) instead of the more common 4
(32 bits).
For Pete's sake, stop using Turbo C++. There are countless better alternatives out there.
Upvotes: 11