0

How does one, computationally and dynamically, derive the 'ths' place equivalent of a whole integer? e.g.:

  • 187 as 0.187
  • 16 as 0.16
  • 900041 as 0.900041

I understand one needs to compute the exact th's place. I know one trick is to turn the integer into a string, count how many places there are (by how many individual characters there are) and then create our future value to multiply against by the tenth's value derived - like how we would on pen and paper - such as:

char integerStr[7] = "186907";
int strLength = strlen(integerStr);
double thsPlace = 0.0F;
for (int counter = 0; counter < strLength; ++counter) {
    thsPlace = 0.1F * thsPlace;
}

But what is a non-string, arithmetic approach to solving this?

4

4 に答える 4

4

疑似コード:

n / pow(10, floor(log10(n))+1)
于 2014-06-11T01:18:45.363 に答える
0

このバージョンのパフォーマンスがどの程度かはわかりませんpow(10, x)が、ほとんどのことは整数演算で行うことができます。正の値または 0 のみを扱っていると仮定します (必要に応じて絶対値を使用してください)。

  int divisor = 1;
  while (divisor < x)
    divisor *= 10; 
  if (divisor > 0)
    return (double)x / divisor; 

上記には、除数がオーバーフローする可能性があるかどうか (その場合は負になる)、x が正であるかどうかなど、いくつかの安全策が必要であることに注意してください。ただし、自分でできると思います。

于 2014-06-11T10:21:06.770 に答える