将float转换为string时,我得到了垃圾值。我不能使用sprintf,因为它需要更多的内存,PIC24单片机的ram大小非常低(128kb)。转换它时会给出一些垃圾值?39.88喜欢这个可能是什么问题。我发布了我的代码......
#include<stdio.h>
#include<string.h>
#include<math.h>
float Distance=0;
char str[15];
unsigned char *ftos(float f,int precision)
{
memset(str,0,sizeof(str));
float ff;
ff = f;
int a,b,c,k,l=0,m,i=0;
// check for negative float
if(f<0.0)
{
str[i++]='-';
f*=-1;
}
a=f; // extracting whole number
f-=a; // extracting decimal part
k = precision;
// number of digits in whole number
while(k>0)
{
l = pow(10.0f,k);
m = a/l;
if(m>0)
{
break;
}
k--;
}
// number of digits in whole number are k+1
/*
extracting most significant digit i.e. right most digit , and concatenating to string
obtained as quotient by dividing number by 10^k where k = (number of digit -1)
*/
for(l=k+1;l>0;l--)
{
b = pow(10.0f,l-1);
c = a/b;
str[i++]=c+48;
a%=b;
}
str[i++] = '.';
/* extracting decimal digits till precision */
for(l=0;l<precision;l++)
{
f*=10.0;
b = f;
str[i++]=b+48;
f-=b;
}
str[i]='\0';
return str;
}
void distance(float lat1, float lon1, float lat2, float lon2)
{
float dlon=0,dlat=0,a=0,c=0,dist=0;
dlon = (lon2 - lon1) * (M_PI / 180.0);
dlat = (lat2 - lat1) * (M_PI / 180.0);
a = pow(sin(dlat/2.0), 2) + cos(lat1*(M_PI / 180.0)) * cos(lat2*(M_PI / 180.0)) * pow(sin(dlon/2.0), 2);
c = 2 * atan2(sqrt(a), sqrt(1-a));
dist = 6367 * c;
Distance += dist;
}
int main()
{
distance(13.00659,80.121212,13.69898,80.256987);
printf("%s\n",ftos(Distance,6));
}
当我在转换后打印距离值时会给出一些垃圾值......为什么?