浮点数转化为字符串

  1. 独立编写函数

浮点数转化为字符串关键点是小数部分的转化,因为当一个小数× 10 后面的数字会变化,此时不容易确定其原有的精度。我们首先设定精度1e-11,使用 float yuan = 0.2589, yuan -= 0.1*(int)(yuan*10), yuan -= 0.01*(int)(yuan*100) 的方法使yuan < 1e-11 此时可完成小数部分的提取。

#include<stdio.h>
#include <math.h>
#include <stdlib.h>

const double eps = 1e-11;

void float_to_str(char *str,double num)
{
    int high;//float_整数部分  
    double low;//float_小数部分 
    char *start=str;
    int n=0;
    char ch[20];
    int i;
    high=(int)num;
    low=num-high;

    while(high>0){
        ch[n++]='0'+high%10;
        high=high/10;
    }

    for(i=n-1;i>=0;i--){
        *str++=ch[i];
    }

    num -= (int)num;
    double tp = 0.1;
    *str++='.';

    while(num > eps){//精度限制 
        num -= tp * (int)(low * 10);
        tp /= 10;
        *str++='0'+(int)(low*10);
        low=low*10.0-(int)(low*10);
    }
    *str='\0';
    str=start;
}
int main()
{
    double a;
    while( ~scanf("%lf", &a) ) {
        char str[20];
        float_to_str(str,a);
        printf("%s\n\n",str);    
    }

}

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

#include<stdio.h>
int main()
{
    float a=12.1047;
    char ch[100];
    sprintf(ch,"%f",a);
    puts(ch);
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值