0

I'm stuck in a Code where I have to convert a temperature given by the user (in Fahrenheit) to degree Celsius. But unfortunately it's formula is not working with C Compiler.

#include<stdio.h>
#include<stdlib.h>
void c_f();
//void f_c();
float c,f,fc,fc1;

int main()
{
    c_f();
    //  f_c();

return 0;
getch();
}
void c_f()
{
    printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
    scanf("%d",&f);

    fc=((5/9)*(f-32));
    printf("\n %f*C",fc);

}
Devanshu
  • 1
  • 3

2 Answers2

0

You have to use the correct format specifier which will be scanf("%f",&f) in this case.

Also fc=((5.0/9.0)*(f-32)), otherwise integer division yields 0.(Integer division truncates).5/9.0 will also work.

It is useless to put getch() after return statement. It will never reach upto that line.


What happens in your version?

Actually when two integers are divided the result is the quotient. If there any fractional part it is discarded. If you divide 5 by 9 the result will be 0.555.... When fractional part discarded it will be 0. So you always get 0.

Whenever you need an outcome of a division not t truncate you must make one of them floating point. That ensures that it(result) will not truncate.


So the program would be

#include<stdio.h>
#include<stdlib.h>

void celciusToFahreinheit();

float fahr_temp,celc_temp;

int main()
{
    celciusToFahreinheit();
    return EXIT_SUCCESS;
}
void celciusToFahreinheit() 
{
    printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
    if( scanf("%f",&fahr_temp) != 1 ){
        fprintf(stderr,"Error in input\n");
        exit(EXIT_FAILURE);
    }
    celc_temp=((5.0/9.0)*(fahr_temp-32));
    printf("\n %f*C",celc_temp);
}

Apart from the problem few things would be - Using readable function name and checking the return value of scanf.

Community
  • 1
  • 1
user2736738
  • 30,591
  • 5
  • 42
  • 56
0
fc=((5/9)*(f-32));

Because 5 and 9 are integers, the arithmetic calculation is done at integer level, thus 5/9 == 0.

You should change it to floating point:

fc = ((5.0f / 9.0f) * (f - 32.0f));

Besides, format specifier %d is used for integers. If you want to read a floating point number, use %f:

scanf("%f", &f);

The result should be right now.

iBug
  • 35,554
  • 7
  • 89
  • 134