problems with an output as double

  • arminho1
  • Newbie
  • Newbie
  • arminho1
  • Posts: 6

Post 3+ Months Ago

hello,
i wrote a program that converts a string of digits to a double value.this works as long as there is no point in the string.for example,when the string is 1234 then the output is 1234.0000
but when the input is like 0.1234 then the program fails.who can help me.

Code: [ Select ]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

double prob1(char * s); 
char inbuf[20];

int main()
{
    char inbuf[20];
  double i;

    while (fgets(inbuf, 20, stdin) != NULL)
    {
            i = prob1(inbuf);
            printf("n = %f\n", i);
  }
}

    double prob1(char * s)
    {
        int i,len;
        double digit,num;
        
        i=0;

        len = strlen(s);
        num = 0;
        while (i<len-1)
        {
            
            digit = s[i] - '0';
            num = num * 10 + digit;
            i++;
            
        }
            return num;
    }
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. double prob1(char * s); 
  5. char inbuf[20];
  6. int main()
  7. {
  8.     char inbuf[20];
  9.   double i;
  10.     while (fgets(inbuf, 20, stdin) != NULL)
  11.     {
  12.             i = prob1(inbuf);
  13.             printf("n = %f\n", i);
  14.   }
  15. }
  16.     double prob1(char * s)
  17.     {
  18.         int i,len;
  19.         double digit,num;
  20.         
  21.         i=0;
  22.         len = strlen(s);
  23.         num = 0;
  24.         while (i<len-1)
  25.         {
  26.             
  27.             digit = s[i] - '0';
  28.             num = num * 10 + digit;
  29.             i++;
  30.             
  31.         }
  32.             return num;
  33.     }


thank you
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9099
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

What is the error you are getting? And are you sure you are able to handle the '.' character correctly?

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 63 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.