#include <iostream>
using namespace std;
static int sflags = 0;
//atof的函数实现。
bool Isnum(char ch)
{
return (ch - '0') >= 0 || (ch - '0') <= 9;
}
float Getnum(char *s,int flags)
{
float count = 0;
int k=0;
while (*s != '\0')
{
if (Isnum(*s) && *s!='.')
count = count * 10 + *s - '0';
if ((Isnum(*s) == 0 && *s != '.') || (Isnum(*s) == 0 && *s == '.' && k == 1))
{
return 0;
}
if (*s == '.')
{
k++;
}
if (k > 0)
k++;
if (k > 7)
return count / 1000000;//多算一位。
s++;
}
for (int i = 0; i < k-2; i++)
{
count /= 10;
}
return count;
}
float my_atof(char *s)
{
float count = 0;
int flags = 0;//记录小数点位数。
if (s == NULL)
{
sflags = 1;
return 0;
}
while (*s == ' ')s++;
if (*s == '\0')return 0;
if (*s == '+')
{
count = Getnum(s + 1,flags);
return count;
}
else if (*s == '-')
{
count = Getnum(s + 1, flags);
return 0 - count;
}
else
{
count = Getnum(s, flags);
return count;
}
return 0;
}
int main()
{
cout << my_atof("-1.123456789") << endl;
cout << atof("-1.123456789") << endl;
}
//atoi的实现。
#include <iostream>
using namespace std;
static int flags = 0;
int Isnum(char ch)
{
return (ch - '0') >= 0 || (ch - '0') <= 9;
}
int Getnum(char *s)
{
long long count = 0;
while (*s != '\0')
{
if (Isnum(*s))
{
count = count * 10 + *s - '0';
if (count >= 0x7fffffff)return 0x7fffffff;
}
if (*s == '.')return count;
if (Isnum(*s) == 0)
return -1;
s++;
}
return count;
}
int my_atoi(char *s)
{
int count = 0;
if (s == NULL)
{
flags = 1;
return 0;
}
if (*s == '\0')return 0;
while (*s == ' ')s++;
if (*s == '+')
{
count = Getnum(s + 1);
if (count == -1)return 0;
else if (count == 0x7ffffffff)
{
return 0x7fffffff;
}
else
{
return count;
}
}
else if (*s == '-')
{
count = Getnum(s + 1);
if (count == -1)return 0;
else if (count == 0x7fffffff)
{
return 0x7fffffff+1;
}
else
{
return 0-count;
}
}
else
{
count = Getnum(s);
if (count == -1)return 0;
return count;
}
}
int main()
{
char *s = new char[20];
cin >> s;
cout << my_atoi(s) << endl;
return 0;
}
C++atoi与atof
最新推荐文章于 2024-10-04 20:09:35 发布