-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString_to_Float.cpp
More file actions
55 lines (47 loc) · 879 Bytes
/
String_to_Float.cpp
File metadata and controls
55 lines (47 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
#include "map"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <stack>
using namespace std;
struct Node{
int val;
Node *left;
Node *right;
Node(int _v):val(_v),left(NULL),right(NULL){}
};
float stringToFloat(string s)
{
float result=0;
int n=s.size();
if(!n)return result;
int sign=1, i=0;
if(s[i]=='-'||s[i]=='+')
{
if(s[i]=='-')sign=-1;
i++;
}
for(;i<n;i++)
{
if(s[i]=='.'){i++;break;}
result=result*10+s[i]-'0';
}
float divisor=10.0;
for(;i<n;i++)
{
result=result+(s[i]-'0')/divisor;
divisor*=10;
}
return sign*result;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<stringToFloat("-874.234")<<endl;
cout<<stringToFloat("+0.234")<<endl;
cout<<stringToFloat("234")<<endl;
return 0;
}