今天面试的题目char*转换为float
总结一下,vs2010下通过测试
代码质量不咋地,求指导更好的算法。
1 // LearnAlgorithm.cpp : Defines the entry point for the console application. 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <string> 7 using namespace std; 8 9 void char2float(char *chrNum, float &fNum) 10 { 11 if (*chrNum <= '0' || *chrNum >= '9' || chrNum == NULL) 12 { 13 cout<<"Usage:输入合法的字符串"; 14 cout<<endl; 15 return; 16 } 17 int num = *chrNum - '0'; 18 chrNum++; 19 int dotIndex=0; 20 int chrLen = strlen(chrNum); 21 while (*chrNum != '\0') 22 { 23 if (*chrNum != '.') 24 { 25 num = num*10 + int(*chrNum-'0'); 26 } 27 else 28 { 29 dotIndex++; 30 } 31 chrNum++; 32 } 33 fNum = (float)num; 34 for (int i=0; i<chrLen-dotIndex; i++) 35 { 36 fNum = fNum/10.0; 37 } 38 } 39 40 int _tmain(int argc, _TCHAR* argv[]) 41 { 42 char *chrNum = "3.14234543"; 43 float result = 0.0; 44 char2float(chrNum, result); 45 cout<<"result:"<<result; 46 cout<<endl; 47 system("pause"); 48 return 0; 49 }