计算带有前导零的数字总和时C中的奇怪行为 [英] Strange behavior in C when calculating sum of digits with leading zeroes
问题描述
我只想在C中编写一个简约程序来计算某个自然数的位数之和(数字之和定义如下:sumOfDigits(123)= 6,sumOfDigits(0)= 0,sumOfDigits(32013) )= 9,依此类推。)
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).
到目前为止,使用以下代码片段一切正常。例如,对于5100,它正确地提供6。但是,为什么14为05100交付(记住领先的0)?
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)?
这里发生了什么?
我查看了数字的二进制表示,但这并没有给我任何信息。 (顺便说一句:以下代码应该在任何地方运行,我猜。)
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;
}
编辑:正如Zaibis所说....前导0表示八进制表示法。 :-)所以:5100_8 == 2624_10
As Zaibis stated .... a leading 0 means octal notation. :-) and so: 5100_8 == 2624_10
推荐答案
前导0表示你想使用八进制数字系统。
A leading 0 means you want to use octal digit system.
所以017也就是小数:15
So 017 i.e. would be decimal: 15
你的05100将是小数:2624
And your 05100 would be decimal: 2624
这篇关于计算带有前导零的数字总和时C中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!