2012-10-24 58 views

回答

2

怎麼樣了這一個簡單的方法?

#include <stdlib.h> /* you need this header for conversion functions */ 
char s[] = "2.03"; 
double a = (int)atoi(s); 
double b = atof(s)-a; 

好的。沒有使用簡單的函數(只有pow和strlen函數)。

#include <stdio.h> 
#include <math.h> 

int main() 
{ 
    char s[] = "2.03"; 
    double a = 0,b = 0; 
    int i,n = 0; 
    char d = 0; 
    for(i = 0; i < strlen(s); i++) /* don't want strlen? for(i = 0; s[i] != '\0'; i++) */ 
    { 
    if(d == 1) 
    { 
     b += (s[i]-'0')/(pow(10,++n)); /* don't want pow? make the function w/ a loop */ 
    } 
    else if(s[i] == '.') 
     d = 1; 
    else 
    { 
     a *= 10; 
     a += s[i]-'0'; /* convert chars to numbers */ 
    } 
    } 
    printf("%f %f",a,b); 
    return 0; 
} 
+0

感謝你的幫助,但不能使用那些 – user1762517

+0

那麼你可以使用什麼?您可以簡單地使用strstr來分割小數,然後創建您自己的解析器。 – u8sand

+0

我必須用數字解析數字.. – user1762517

2

使用strtodmodf

#include <stdlib.h> 
#include <math.h> 

double d = strtod(s, NULL); 
double a; 
double b = modf(d, &a); 
0

那麼,關於類似下面的功能。

void makeTwoPieces (char *str, double *dMost, double *dLeast) 
{ 
    double dMultiplier; 
    *dMost = *dLeast = 0.0; 

    for (; *str; str++) { 
    if (*str == '.') { 
     break; 
    } else if (*str >= '0' && *str <= '9') { 
     *dMost *= 10; 
     *dMost += (*str - '0'); 
    } 
    } 
    dMultiplier = 1.0; 
    for (; *str; str++) { 
    if (*str >= '0' && *str <= '9') { 
     dMultiplier /= 10; 
     *dLeast += (*str - '0') * dMultiplier; 
    } 
    } 
} 

然後,你可以在一個測試工具,使用此功能如下所示:

int main(int argc, char * argv[]) 
{ 
    double d1, d2; 
    char *str = "2.03"; 
    makeTwoPieces (str, &d1, &d2); 
    return 0; 
}