float转换为字符串
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <math.h>
using namespace std;
char ch[20];
int cnt = 0;
int split_int(int num)
{
int temp1,temp2;
char ch1[6];
int i=0;
while(num%10)
{
temp1 = num%10;
ch1[i] = temp1+'0';
i++;
num=num/10;
}
for(int k=i-1;k>=0;k--)
{
ch[cnt++] = ch1[k];
}
return 1;
}
bool float_to_str(float num)
{
int temp=(int)num,tmp;
int previout;
int temp1 = temp;
int temp2 = temp;
int i = 0, j = 0;
ch[cnt++]='.';
while(temp != 0)
{
previout = (int)num;
num *= 10;
temp=(int)num;
// cout<<(int)num<<endl;
temp = temp-(previout*(int)pow(10,1));
ch[cnt++] = temp+'0';
if((j > 5) || (temp < 0))
{
break;
}
j++;
}
ch[cnt-1] = '\0';
return true;
}
int main(void)
{
float num = 74.77;
/*
ostringstream oss;//创建一个流
oss<<num;//把值传递如流中
string result=oss.str();//获取转换后的字符转并将其写入result
cout<<result<<endl;*/
split_int(int(num));
float_to_str(num);
cout<<ch<<endl;
return 0;
}
/*
#include <stdio.h>
int main(void)
{
char ch[12];
int i;
sprintf(i,"%f",2.21f);
printf("%s\n",ch);
return 0;
}*/