zoukankan      html  css  js  c++  java
  • 浮点数转化为字符串

      (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 }
  • 相关阅读:
    UISegmentControl
    UISegmentControl,UISwich,UIPageControl
    UIPageControl,UISlider
    UISlider
    触摸事件,响应者链和手势
    NIO Socket
    处理多线程问题的工具类
    Java多线程疑难点
    软中断和硬中断的联系与区别
    进程—内存描述符(mm_struct)
  • 原文地址:https://www.cnblogs.com/johnleo/p/float_to_string.html
Copyright © 2011-2022 走看看