您的位置:首页 > 职场人生

一道百度面试题: C /C ++ 中一次遍历将string转float (带小数点)

2011-08-25 16:24 375 查看
写了一段代码,“123.456”倒是可以,长点的数据貌似就不行啦:

#include <iostream>
#include <string>
int my_power(int n)
{
int temp = 1;
while (n--)
temp *= 10;
return temp;
}
float string_to_float(std::string s)
{
int n = s.size();
int i = 0;
float temp1 = 0.0f,temp2=0.0f;
while (i < n && s[i] != '.')
{
temp1 = (s[i]-'0')+temp1*10;
++i;
}
int j = ++i;
while (j < n)
{
temp2 = (s[j]-'0')+temp2*10;
++j;
}
return temp1+temp2/my_power(n-i);
}

int main()
{
std::string s = "123.456";
std::cout << string_to_float(s) << std::endl;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: