Strange behavior in C when calculating sum of digits with leading zeroes

老子叫甜甜 提交于 2019-11-27 08:24:27

问题


I just wanted to write a minimalistic program in C to calculate the sum of digits of some natural number (the sum of digits is defined as follows: sumOfDigits(123) = 6, sumOfDigits(0) = 0, sumOfDigits(32013) = 9, and so on).

So far, everything is ok with the following code snippet. For example, for 5100 it delivers 6, correctly. But, why is 14 delivered for 05100 (remember the leading 0)?

What's going on here?

I had a look at the binary representation of the numbers, but that didn't give any information to me. (BTW: The following code should run anywhere, I guess.)

#include <stdio.h>

unsigned int sumOfDigits(unsigned int n) {
    int retval = 0;
    while (n > 0) {
        retval += n % 10;
        n/=10;
    }
    return retval;
}

int main() {
    printf("OK: %u\n", sumOfDigits(5100u));
    printf("WTF: %u",  sumOfDigits(05100u));
    return 0;
}

EDIT: As Zaibis stated .... a leading 0 means octal notation. :-) and so: 5100_8 == 2624_10


回答1:


A leading 0 means you want to use octal digit system.

So 017 i.e. would be decimal: 15

And your 05100 would be decimal: 2624



来源:https://stackoverflow.com/questions/18443054/strange-behavior-in-c-when-calculating-sum-of-digits-with-leading-zeroes

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