如何将一个数字转换为0.mynumber

How to convert a number to 0.mynumber

本文关键字:转换 数字 mynumber 一个      更新时间:2023-10-16

如何将数字转换为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