0

如何将数字转换为 0。和数字?

所以

int i = 50;
float a = 0.i //wrong code :D

要不然是啥?我该怎么做?

4

3 回答 3

3
float a = i;
while( a >= 1.0f ) a /= 10.0f;
于 2013-04-05T16:34:53.140 回答
1

这很丑,但我认为这有效:

    int i = 50;
    std::stringstream ss;
    ss << "0." << i;
    float a;
    ss >> a;
于 2013-04-05T16:39:17.537 回答
1

关于什么:

#include <cmath>
#include <initializer_list>
#include <iostream>

float zero_dot( float m ) {
   return m / pow( 10.0, floor( log( m ) / log( 10.0 ) ) + 1 );
}

int main() {

   for( auto const & it: { 5.0, 50.0, 500.0, 5509.0, 1.0 } ) {
      std::cout << it << ": " << zero_dot( it ) << std::endl;
   }

   return 0;
}

输出是:

5: 0.5
50: 0.5
500: 0.5
5509: 0.5509
1: 0.1

计算不使用任何循环。

于 2013-04-05T21:21:25.990 回答