problems with an output as double

  • arminho1
  • Newbie
  • Newbie
  • No Avatar
  • Joined: Oct 04, 2003
  • Posts: 6
  • Status: Offline

Post October 26th, 2003, 9:09 pm

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
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post October 26th, 2003, 9:09 pm

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Joined: Dec 20, 2002
  • Posts: 8925
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Post October 30th, 2003, 7:11 pm

What is the error you are getting? And are you sure you are able to handle the '.' character correctly?
Ozzu Hosting - Want your website on a fast server like Ozzu?

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 225 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
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.