Find the sum of digits of a number(in c)

梦想与她 提交于 2021-02-04 21:36:37

问题


I need to find the sum of the digits of a number. For example, the sum of the digits of the number 1123 is 1+1+2+3 =7

My idea:

1)User enters and integer

2)I calculate the number of digits in the number(in case above - 4 digits)

3)Than using for loop I divide users number by 10 to the power of 1,2...till the number of digits(not including the last one) and sum the numbers.

Here is my code:

int main (void)
{
    int result,sum,n;
    int div = 10,counter = 0,number;

    printf("Enter the integer:");
    scanf("%i",&number);
    while(result >0){
        result = number/div;
        div *= 10;
        ++counter;
    }
    printf("The number consists of %i digits\n",counter);
    sum = 0;

    for(n=1;n<counter;++n){
        sum += number/pow(10,n);
    }
    printf("%i",sum);

    return 0;


}

the first part(while loop) separately works correct. But together with second part(for loop) it gives me incorrect result(0 digits from the while loop and the sum is also zero). Can you explain why does it happen? How can I correct my solution?

P.S I know that exist more efficient solutions of my problem, but i want to use my own algorithm.


回答1:


Several problems here:

  • When you first enter the while loop, result has not been initialized. Attempting to read an uninitialized variable is undefined behavior.
  • When you do the division, you aren't adding digits. You're adding the number divided by successive powers of 10. In the case of 1123, you're actually adding 112 + 11 + 1. You need to use modulus instead of division to get the digits.

You can do the adding and counting of digits in a single loop as follows:

sum = 0;
while(number > 0){
    sum += number % 10;
    number /= 10;
    ++counter;
}
printf("The number consists of %i digits\n",counter);
printf("%i",sum);



回答2:


much simpler:

result = number;
sum = 0;
counter = 0;
while(result != 0){
    sum += result % 10;
    result /= 10;
    ++counter;
}

printf ("Counter:%d sum:%d\n", counter, sum);



回答3:


First of all, for best debugging, use a number which has different digits, like 12345.

To do debugging, calculate and print the digit separately from accumulating it. That is, instead of sum += <... complex code ...>, do it like this:

int digit = ...
printf("Next digit is %i\n", digit);
sum += digit;

Also (you should discover this by debugging, but it's obvious enough to note directly), your algorithm for calculation of digits is wrong. Do something like this:

int div = 1;
for (...)
{
    digit = number / div % 10;
    div *= 10;
}

Note that I don't use pow here, because pow uses floating-point arithmetic, which has limited accuracy. If your int has 64 bits of precision (unlikely but possible), floating-point will calculate nonsense for large numbers (it has only 53 bits of precision).




回答4:


There are many errors in the code, but overall the whole approach is wrong. Counting the digits is unnecessary.

A simpler way would be:

unsigned temp = number, sum = 0;
while (temp) {
  sum += temp % 10;
  temp /= 10;
}

Notice that you know when to stop looping because temp becomes 0 (temp as a condition is equivalent to temp != 0). You don't need to know the number of digits in advance.




回答5:


If going with your code, this'll work:

for(n=1;n<=counter;++n){
    sum += number%10;
    number /= 10;
}
printf("%d",sum);



回答6:


Simpler solution:

int c, n=0, sum=0;
printf("Enter number");
while((c=getchar())!='\n') {    // IMPORTANT: '\n' in unix, '\r' in windows
    if(c<'0' || c>'9') {
        printf("Bad value");
        break;
    }
    sum+=c-'0';    // c is the ASCII code of the digit, so you have to subtract an offset
    n++;
}
printf("Number of digits: %d", n);
printf("Sum of digits: %d", sum;


来源:https://stackoverflow.com/questions/39230648/find-the-sum-of-digits-of-a-numberin-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!