一道百度面试题: 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; }
相关文章推荐
- 2012百度实习生面试题一道,打乱100个数的顺序,越乱越好 .
- 一道百度的面试题--写一个函数,对一个数字如(1000000),每隔3位添加一个','
- 写出float x 与“零值”比较的if语句——一道面试题分析
- 回顾JavaSE(5)-String(4)7行代码分析一道关于String拼接的经典面试题
- 一道百度面试题
- 面试经之一道淘汰85%面试者的百度开发者面试题
- 一道淘汰85%面试者的百度开发者面试题
- 一道面试题:StringBuffer a=new StringBuffer ("A"); StringBuffer b=new StringBuffer
- 一道百度面试题,关于海量数据处理,你有更好的方法吗?
- 一道简单的百度面试题遇到的问题
- 一道淘汰85%面试者的百度开发者面试题
- 解一道百度面试题
- 2011百度实习生面试题-二叉树“弓”字形遍历
- 一道印象深刻的面试题:String参数传递问题
- 日志系统:字段类型的思考——String(字符串)、datetime(日期时间)、ip、int(整数)、float(小数)
- 百度面试题,一天一道慢慢来
- 一道淘汰85%面试者的百度开发者面试题-我就是想知道正确的答案.
- 2014-05-08一道淘汰85%面试者的百度开发者面试题
- 一道百度面试题——位运算
- 【题目36】百度的一道面试题-找到攻击IP