将float转成string

昨天一个同学来公司面试,是我推荐的。面试官是我的两个同事,他们出了一道题,将一个float转成string。我的那个同学没有写出来,回来后问我的想法,我花了几分钟的时间,粗略写了一下,代码如下:
#include 
#include 

using namespace std;

string flot2str(float f)
{
	if (f == 0)
		return "0";
	string s;
	int x = (int)f;
	int d;
	while (x > 0)
	{
		d = x % 10;
		x /= 10;
		s = (char)(d + '0') + s;
	}
	s += ".";
	float y = f - (int)f;
	while (y > 0)
	{
		y *= 10;
		d = (int)y;
		s += (char)(d + '0');
		y -= d;
	}
	return s;
}

int main()
{
	float f = 0;
	cout << flot2str(f);
	system("pause");
	return 0;
}
由于float的精度问题,并不是很准确,应该有更好的方法,我觉得可以参考一下printf的实现。

posted on 2011-12-22 22:41  小橋流水  阅读(1859)  评论(0编辑  收藏  举报

导航