Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

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

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
", 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...