mercredi 1 juillet 2015

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

I wrote a simple program to convert degrees Fahrenheit to degrees Celsius using functions (been working w/ Python for 2 weeks, wanted to refresh myself):

#include <stdio.h>
#include <math.h>

int temp_change(fahrenheit);

int main()
{
    while(1)
    {
        int fahrenheit;
        printf("Please input a temperature in Fahrenheit.\n");
        scanf("%d", &fahrenheit); //Obtains degrees F value
        printf("%d\n", temp_change(fahrenheit));

    }
}
//Function to change temperature
int temp_change(fahrenheit)
{
    int centigrade;
    centigrade = 5*(fahrenheit - 32)/9; //Changing the temperature
    return centigrade;
}

and it gave me correct answers (to the nearest degree). However, I wanted exact answers, so I changed all the ints to floats (except for int main(). Now the only thing the program will give me is -18.000000, no matter what input I give it. The best way to summarize what I tried: I tried different combinations of the ints and the floats but with no luck. I would suspect that it had something to do with printf("%d\n", temp_change(fahrenheit)); but it gave me correct answers when everything was int, so I don't know. XD Thanks in advance for any help!

Aucun commentaire:

Enregistrer un commentaire