#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
原文地址:http://10725723.blog.51cto.com/10715723/1758174