一道百度面试题 ------------ C /C ++ 中一次遍历将string转float （带小数点）

0

` for(; *str != '\0' && *str >= '0' && *str <= '9'; str ++) value = value * 10 + (*str - '0');`
`那么有小数点的情况想怎么写？ `

wtx | 初学一级 | 园豆：160

0

`#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;}`

hailong | 初学一级 |园豆：70 | 2011-08-25 16:19

wtx | 园豆：160 (初学一级) | 2011-08-25 17:36
#include
#include
#include
using namespace::std;

const int MAX = 10;

int my_power(int n)
{
if(n <= 0)
return 1;
int temp = 1;
while (n--)
temp *= 10;
return temp;
}

float convert(const char* str)
{
float sum1 = 0.0;
float sum2 = 0.0;
int i = 0;
int idx = 0;
int len = strlen(str);

while(str[idx] != '.' && str[idx] != '\0')
idx++;

while(i < idx)
{
sum1 = sum1 * 10 + (str[i]-'0'); //整数部分
i ++;
}
i = idx + 1;
if(i < len)
{
while(i < len)
{
sum2 = sum2 * 10 + (str[i]-'0');
i ++;
}
}

return (sum1+sum2/my_power(len - idx - 1));
}
int main()
{
float result = 0.0;
char str[MAX];
cin >> str;
result = convert(str);
cout << result << endl;
return 0;
}
wtx | 园豆：160 (初学一级) | 2011-08-25 18:41

wtx | 园豆：160 (初学一级) | 2011-08-25 18:43

您需要登录以后才能回答，未注册用户请先注册