This program doesn't work properly for decimal

2019-07-26 04:58发布

问题:

The below code is used to count number of digit in a given decimal. The problem is that it doesn't count digits more than 10.

int NumDigits(int n) {
  int digits = 0;
  if (n <= 0) {
    n = -n;
    ++digits;
  }

  while (n) {
    n /= 10;
    ++digits;
  }

  return digits;
}

回答1:

It seems like your toolchain has a 32-bit int type. The maximum value representable in such a type is 231-1, or 2,147,483,647. As you can see, that's a 10-digit number. You'll need to use a different type that supports larger numbers if you want to use this kind of an algorithm.



回答2:

That's a 32 bit integer, which has a maximum amount of 2,147,483,647. You might want to look into using 64 bit integers or other solutions.



回答3:

Try long for the argument type.

As Jonathan already stated in his comment an int cannot contain a number with more than 10 digits.



回答4:

The reason is that your parameter is of the type int, which is limited in size. Most likely you have Int32 (you can find it out with sizeof(int) which gives you the size in byte) which goes up to 2147483647 and then overflows to the negative value -2147483648.

Example: 
int i = 2147483647;
i = i+1;
printf("%d\n",i);

gives you the output: "-2147483648"



标签: c decimal digits