Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Programming help: Centrigrade to Fahrenheit
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Ceevu




PostPosted: Sat May 20, 2006 12:43 am   Post subject: Programming help: Centrigrade to Fahrenheit

Am new to programming and am studying some C language through a book (Practical C Programming by Steve Oualline).

I've come across an exercise which I can't quite get to work out.

I use the MinGW 4.1 compiler and run in WinXP. Here's the code:

code:
/* This program converts Centigrade to Fahrenheit */

#include <stdio.h>

char input[100];        /* Input from keyboard */
float celcius;    /* declaraction of Celcius */
float F;                        /* declaration of Fahrenheit */

int main ()
{
    printf ("Input a centrigrade to convert to Fahrenheit: ");

    /* Get the input from user and convert to number */

    fgets (input, sizeof(input), stdin);
    sscanf (input, "%f", &celcius);

    F=(9/5)*celcius+32; /* Forumula for C to F */

    printf ("%f converted into Fahrenheit is %f.\n", celcius, F);

    return (0);

}


The problem is when I run the program it does not give the correct answer. Any suggestions?

Thanks in Advance Smile
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Sat May 20, 2006 2:50 am   Post subject: (No subject)

Odd type casting issue. Lots of languages face this problem, like C, C++, Java, Ruby, etc. It has to do with the rather weak type system and the cast priority given to literals. Languages like Haskell and ocaml for example do not suffer the same ill effects (they have a stricter type system).

Change it to: F = (9.0/5)*celcius+32;
i.e use at least one floating point literal in that multiplication expression, so as to hint to the compiler we do not want that expression to be casted to an integer.

Actually make it a habit to always use floating point literal when dealing with floats or doubles.
Ceevu




PostPosted: Sat May 20, 2006 9:39 am   Post subject: (No subject)

Worked like a charm, thanks a bunch! Smile
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: