c - int produces near correct answer, but float just gives -18.000 -


i wrote simple program convert degrees fahrenheit degrees celsius using functions (been working w/ python 2 weeks, wanted refresh myself):

#include <stdio.h> #include <math.h>  int temp_change(fahrenheit);  int main() {     while(1)     {         int fahrenheit;         printf("please input temperature in fahrenheit.\n");         scanf("%d", &fahrenheit); //obtains degrees f value         printf("%d\n", temp_change(fahrenheit));      } } //function change temperature int temp_change(fahrenheit) {     int centigrade;     centigrade = 5*(fahrenheit - 32)/9; //changing temperature     return centigrade; } 

and gave me correct answers (to nearest degree). however, wanted exact answers, changed ints floats (except int main(). thing program give me -18.000000, no matter input give it. best way summarize tried: tried different combinations of ints , floats no luck. suspect had printf("%d\n", temp_change(fahrenheit)); gave me correct answers when int, don't know. xd in advance help!

the integer version not give nearest converted temperature, rounds temperature toward 0.

there problem in code: prototype temp_change incomplete, forgot specify type of argument.

here corrected version using floats:

#include <stdio.h>  float temp_change(float fahrenheit);  int main(void) {     (;;) {         float fahrenheit;         printf("please input temperature in fahrenheit.\n");         if (scanf("%f", &fahrenheit) == 1) {//obtains degrees f value             printf("%f\n", temp_change(fahrenheit));         }     } } //function change temperature float temp_change(float fahrenheit) {     float centigrade;     centigrade = 5 * (fahrenheit - 32) / 9; //changing temperature     return centigrade; } 

note should using double precision floating point numbers. incidentally, return value of temp_change() converted double when passed printf. format specifier %f takes float* scanf, takes double printf.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -