如何将数字转换为 0。和数字?
所以
int i = 50;
float a = 0.i //wrong code :D
要不然是啥?我该怎么做?
float a = i;
while( a >= 1.0f ) a /= 10.0f;
这很丑,但我认为这有效:
int i = 50;
std::stringstream ss;
ss << "0." << i;
float a;
ss >> a;
关于什么:
#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
计算不使用任何循环。