//我写的转换函数,包括了一个测试函数,自己看吧,可以把输出语句的注释去掉,查看调试效果
int f2s(float f, char** buf)
{
char bf[100];
int i=0;
int integer;
float decimal;
integer = (int)f;
decimal = f - integer;
//cout<<"整数部分:"<<integer<<endl;
//cout<<"小数部分:"<<decimal<<endl;
//cout<<"先确定正负号,如果是负号就把字符串的第一个赋值为'-',值取正,索引+1 "<<endl;
if(f<0)
{
//printf("%d %c\n", '1', '1');
//printf("%d %c\n", '-', '-');
bf[0] = 45;
integer = -integer;
decimal = -decimal;
i++;
}
int top=0;
int stack[100];
//cout<<"-------------------------------"<<endl;
//cout<<"处理整数"<<endl;
while( integer != 0 )
{
stack[top] = integer%10;
top++;
integer /= 10;
//
cout<<"当前整数值:"<<integer<<endl;
}
//
cout<<"当前栈:"<<endl;
//
for(int t=0; t<top; t++)
//
cout<<t<<"="<<stack[t]<<endl;
//
cout<<"填入字符串"<<endl;
for(int t=top-1; t>=0; t--)
{
//因为1是49所以n是n+48
bf[i] = stack[t]+48;
//
printf("%d ", bf[i]);
i++;
}
cout<<endl;
for(int t=0; t<i; t++)
{
//
printf("%s", bf);
}
//
cout<<"-------------------------------"<<endl;
bf[i] = '.';
i++;
//cout<<"处理小数"<<endl;
//decimal
//只计算到6位
for(int t=0; t<7; t++)
{
bf[i] = int(decimal*10.0f) + 48;
//
cout<<"()"<< int(decimal*10.0f)<<endl;
i++;
decimal = decimal*10.0f;
decimal = decimal - (int)decimal;
//
cout<<"当前小数部分:"<<decimal<<endl;
}
//cout<<"===========end================="<<endl;
//cout<<bf<<endl;
*buf = (char*)malloc(i+1);
for(int t=0; t<i; t++)
(*buf)[t] = bf[t];
(*buf)[i] = '\0';
//返回字符串的长度
return i+1;
}
void test_f2s()
{
char *buf;
float f = -31234.12345678f;
float f2 = 31234.7654321f;
printf("%f\n", f);
printf("%f\n", f2);
f2s(f, (char**)&buf);
cout<<"1: "<<buf<<endl;
free(buf);
f2s(31234.7654321, (char**)&buf);
cout<<"2: "<<buf<<endl;
free(buf);
f2s(f, (char**)&buf);
for(int i=0; buf[i] != '\0'; i++)
{
printf("%c", buf[i]);
}
cout<<endl;
free(buf);
}
void main()
{
test_f2s();
}