您的位置:首页 > 其它

字符串转浮点数 字符串转整型数

2016-05-26 12:28 375 查看
#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
double AtOf(const char* ptr);
double AtOi(const char* ptr)
{
assert(ptr);
double value = 0.0;
double sign = 0;
while (*ptr == ' ')//跳过空格
{
ptr++;
}
if (*ptr == '+' || *ptr == '-')
{
sign = (*ptr == '-') ? -1 : 1;
ptr++;
}
while (*ptr <= '9'&& *ptr >= '0')
{
value = value * 10 + *ptr - '0';
ptr++;
}
return sign*value;
}
void test1()
{
char *p = "   +1234.6978";
double ret = AtOf(p);
printf("%lf\n", ret);
}
void test2()
{
char *p = " -1234.6978";
double ret = AtOi(p);
printf("%lf\n", ret);
}
int main()
{
test2();
system("pause");
return 0;
}
double AtOf(const char * ptr)
{
assert(ptr);
double value = 0.0;
double power = 0.0;
    int sign = 0;
while (*ptr ==' ' )
{
++ptr;
}
if (*ptr == '+' || *ptr == '-')
{
sign = (*ptr == "-") ? -1 : 1;
++ptr;
}
while (*ptr >= '0' && *ptr <= '9')
{
value = value * 10 + (*ptr) - '0';
ptr++;
}
power = 1;
if (*ptr == '.')
{
++ptr;
while (*ptr >= '0' && *ptr <= '9')
{
value = value * 10 + (*ptr) - '0';
power *= 10;
ptr++;
}
}
return sign*value / power;
}
本文出自 “fun” 博客,请务必保留此出处http://10725723.blog.51cto.com/10715723/1758174
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: