I'm trying to get every other digit from a user-inputted number. And then find their sum. For example, 123456. I want to get 5,3, and 1. Then find their sum. This is my function for that:
int getSum(long userInput) // user input being passed as an argument.
{
long userInput1 = userInput;
long sumOfNum = 0 ;
while(userInput1 != 0)
{
userInput1 = userInput1 / 10;
sumOfNum = userInput1 % 10;
}
printf("%ld\n",sumOfNum);
}
This doesn't work for all of the numbers, for example; with 12345, I am expecting 6. But the output is 10.
Where did I go wrong?
[Edit- How I did it? (based on the answer from Fe2O3) I need another division. So:
while(userInput1 != 0)
{
userInput1 = userInput1 / 10;
sumOfNum = (userInput1 % 10);
userInput1 = userInput1 / 10; // this one
}
printf("%ld\n",sumOfNum);
return sumOfNum;
}
CodePudding user response:
To get every other digit...
int getSum( long val ) {
int sum = 0;
for( val /= 10; val; val /= 100 )
sum = val % 10;
printf( "%d\n", sum );
return sum; // missed this in previous version
}
EDIT:
After it was pointed out that 'sum' went out of scope after the for()
terminated, the code has been adapted to have fewer division operations.
CodePudding user response:
An alternative approach. Slower, but simpler to understand.
#include <stdio.h>
#include <string.h>
int getSum(long val) {
char buf[40]; // Must be big enough, and 40 is big enough for 128 bit numbers
sprintf(buf, "%d", val); // Convert to string
int sum=0;
for(int i=0; i<strlen(buf); i )
sum = buf[i] - '0';
return sum;
}