字符串转浮点数https://blog.csdn.net/qq_34793133/article/details/80550283
(1)在不调用库函数的情况下,把浮点数转化为字符串的难点就在,把小数转化为字符串。因为浮点数的精度问题,当我们对浮点数进行乘10操作的时候,浮点数尾数数值可能就会发生变化,如float a=12.1047; a*=10;输出a=121.046997。所以在把浮点数的小数转化为字符串时要对精度进行限制。
#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)如果使用库函数sprintf(),这个题目就很简单了,直接调用sprintf(),将浮点数格式化输出到指定字符串就好了。
sprintf( char *buffer, const char *format, [ argument] … );【sprintf()使用详情请baidu】
#include<stdio.h> int main() {
float a=12.1047; char ch[100]; sprintf(ch,"%f",a); puts(ch);
}