• 浮点数转化为字符串


      (1)在不调用库函数的情况下,把浮点数转化为字符串的难点就在,把小数转化为字符串。因为浮点数的精度问题,当我们对浮点数进行乘10操作的时候,浮点数尾数数值可能就会发生变化,如float a=12.1047; a*=10;输出a=121.046997。所以在把浮点数的小数转化为字符串时要对精度进行限制。

     1 #include<stdio.h>
     2 #include <math.h>
     3 #include <stdlib.h>
     4 
     5 const double eps = 1e-11;
     6 
     7 void float_to_str(char *str,double num)
     8 {
     9     int high;//float_整数部分  
    10     double low;//float_小数部分 
    11     char *start=str;
    12     int n=0;
    13     char ch[20];
    14     int i;
    15     high=(int)num;
    16     low=num-high;
    17     
    18     while(high>0){
    19         ch[n++]='0'+high%10;
    20         high=high/10;
    21     }
    22     
    23     for(i=n-1;i>=0;i--){
    24         *str++=ch[i];
    25     }
    26     
    27     num -= (int)num;
    28     double tp = 0.1;
    29     *str++='.';
    30     
    31     while(num > eps){//精度限制 
    32         num -= tp * (int)(low * 10);
    33         tp /= 10;
    34         *str++='0'+(int)(low*10);
    35         low=low*10.0-(int)(low*10);
    36     }
    37     *str='';
    38     str=start;
    39 }
    40 int main()
    41 {
    42     double a;
    43     while( ~scanf("%lf", &a) ) {
    44         char str[20];
    45         float_to_str(str,a);
    46         printf("%s
    
    ",str);    
    47     }
    48     
    49 }
    View Code

      (2)如果使用库函数sprintf(),这个题目就很简单了,直接调用sprintf(),将浮点数格式化输出到指定字符串就好了。

    sprintf( char *buffer, const char *format, [ argument] … );【sprintf()使用详情请baidu】

    1 #include<stdio.h>
    2 int main()
    3 {
    4     float a=12.1047;
    5     char ch[100];
    6     sprintf(ch,"%f",a);
    7     puts(ch);
    8 }
  • 相关阅读:
    数据仓库 VS 数据库
    准确率,精确率,召回率,F-measure 之间的关系
    OpenCV——查找、绘制轮廓
    OpenCV——仿射变换
    OpenCV函数 重映射
    Hough变换原理
    霍夫变换(直线检测、圆检测)
    边缘检测算子+滤波总结
    图像滤波—opencv函数
    图像滤波
  • 原文地址:https://www.cnblogs.com/johnleo/p/float_to_string.html
Copyright © 2020-2023  润新知