idastan97

CSCI151 L21 P2

Oct 23rd, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4.  
  5. double strToDouble(char str[]){
  6.     int i=0;
  7.     double result=0;
  8.     int p=0;
  9.     _Bool negativeSignP=0;
  10.     _Bool negativeSignN=0;
  11.     if (str[i]=='-'){
  12.         negativeSignN=1;
  13.         i++;
  14.     }
  15.     for ( ; str[i]>='0' && str[i]<='9'; i++){
  16.         result=result*10+str[i]-'0';
  17.     }
  18.     if (str[i]=='.'){
  19.         int k=10;
  20.         i++;
  21.         for ( ; str[i]>='0' && str[i]<='9'; i++, k*=10){
  22.             result=result+(double)(str[i]-'0')/k;
  23.         }
  24.     }
  25.     if (str[i]=='e'){
  26.         i++;
  27.         if (str[i]=='-'){
  28.             negativeSignP=1;
  29.             i++;
  30.         }
  31.         for ( ; str[i]>='0' && str[i]<='9'; i++){
  32.             p=p*10+str[i]-'0';
  33.         }
  34.         int j;
  35.         for (j=0; j<p; j++){
  36.             if (negativeSignP)
  37.                 result/=10.0;
  38.             else
  39.                 result*=10.0;
  40.         }
  41.     }
  42.     if (negativeSignN){
  43.         result*=(-1);
  44.     }
  45.     return result;
  46. }
  47.  
  48. int main(void) {
  49.     char n[50];
  50.     scanf("%s", n);
  51.     printf("%f", strToDouble(n));
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment