- 独立编写函数
浮点数转化为字符串关键点是小数部分的转化,因为当一个小数× 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);
}