将一个浮点数转换为字符串(有bug,不知道什么原因)

/*
 * 将一个浮点数转换为字符串
 * 例如:123.456转换为"123.456"
 */
#include<stdio.h>
#include<stdlib.h>

char *convert(double d)
{
	//代表浮点数d的整数部分
	int d1=(int)d;
	//代表浮点数d的小数部分
	double d2=d-d1;
	//用来存储浮点数d的整数部分
	int a[20];
	//用来存储浮点数d的小数部分
	int b[20];
	int aloc=0;
	int bloc=0;
	int i=0;
	//将整数部分装入数组a中
	while(d1>0)
	{
		int temp=d1%10;
		a[aloc]=temp;
		aloc++;
		d1/=10;
	}
	//将小数部分装入数组b中
	while(d2>0.00001)
	{
		d2*=10;
		int temp=(int)d2;
		b[bloc]=temp;
		bloc++;
		d2-=temp;
	}

	printf("aloc=%d\n",aloc);
	printf("bloc=%d\n",bloc);

	//申请内存空间(多申请两个空间是为了存放'.'和'\0')
	char *s=(char *)malloc(aloc+bloc+2);
	if(s==NULL)
	{
		printf("create fail!|n");
		exit(1);
	}
	char *t=s;
	while(aloc>0)
	{
		*t=a[aloc-1]+'0';
		aloc--;
		t++;
	}
	*t='.';
	t++;
	while(i<bloc)
	{
		*t=b[i]+'0';
		i++;
		t++;
	}
	*t='\0';
	return s;
}

int main()
{
	double d=123.456;
	char *s=convert(d);
	printf("%s\n",s);
	return 0;
}

当输入double d=123.456时,输出结果为123.456

当输入double d=123.4567时,输出结果和预期的不一样,不知道为什么会产生这个bug???????????? 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值