Programming help: Centrigrade to Fahrenheit
Author |
Message |
Ceevu
|
Posted: 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 Smile](http://compsci.ca/v3/images/smiles/icon_smile.gif) |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
rizzix
|
Posted: 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. |
|
|
|
|
![](images/spacer.gif) |
Ceevu
|
Posted: Sat May 20, 2006 9:39 am Post subject: (No subject) |
|
|
Worked like a charm, thanks a bunch! ![Smile Smile](http://compsci.ca/v3/images/smiles/icon_smile.gif) |
|
|
|
|
![](images/spacer.gif) |
|
|