今天面试的题目char*转换为float

本文提供了一种改进的字符转浮点数算法实现,并详细解释了其实现过程。通过优化输入验证和数值转换逻辑,提高了代码效率和准确性。适合VS2010环境下使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结一下,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 }
View Code

 

转载于:https://www.cnblogs.com/chenxiaojian/p/3417592.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值