2016-01-21 99 views
2

在K & R第71页中,atof函数使用数组索引。我试图使用指针算法实现相同的功能(因为它使感觉像一个坏蛋:))。K&R的这个实现有什么问题?

double atof(char *str) 
{ 
    int sign; 
    double number = 0.0, power = 1.0; 

    while(isspace(*str)) 
    ++str; 

    sign = (*str == '-') ? -1 : 1; // Save the sign 

    if(*str == '-' || *str == '+') // Skip the sign 
    str++; 

    while(isdigit(*str)) // Digits before the decimal point 
    { 
    number = 10.0 * number + (*str - '0'); 
    str++; 
    } 

    if(*str == '.') // Skip the decimal point 
    str++; 

    while(isdigit(*str)) // Digits after the decimal point 
    { 
    number = 10.0 * number + (*str - '0'); 
    power *= 10.0; 
    str++; 
    } 


    return sign * number/power; 

}

在主

printf("%g\n", atof(" 123123.123")); // Outputs 123123 
printf("%g\n", atof(" 1234.1222")); // Outputs 1234.12 

什么是我的错!

回答

4

atof()执行情况良好。但是使用%g的printf删除了部分结果。

6是默认的,如果你没有明确指定它。由于产生的值具有更高的精度,因此会丢失。指定精度:

printf("%.12g\n", atof(" 123123.123")); 
printf("%.12g\n", atof(" 1234.1222")); 

或者,你可以使用%f(这将打印虽然尾随零)。

+0

该死的我应该知道的:)。那么%g的默认精度是6位数?! – MAA

+0

是(包括*小数*和小数部分的总宽度)。 6是大多数printf精度的默认值。您可以在这里阅读C标准中的详细信息:http://port70.net/~nsz/c/c11/n1570.html#7.21.6.1p8 –

+0

非常感谢你。特别是对于包括这个标准。 – MAA