C program to convert Fahrenheit to Celsius always prints zero

后端 未结 7 982
无人及你
无人及你 2020-11-22 07:09

I need some help with a program for converting Fahrenheit to Celsius in C. My code looks like this

#include 
int main(void)
{
    int fahrenhe         


        
相关标签:
7条回答
  • 2020-11-22 07:42

    5/9 will result in integer division, which will = 0

    Try 5.0/9.0 instead.

    0 讨论(0)
  • 2020-11-22 07:43

    When dealing with floats, it needs to be 5.0f / 9.0f.

    When dealing with doubles, it needs to be 5.0 / 9.0.

    When dealing with integers, remainders/fractions are always truncated. 5 / 9 results between 0 and 1, so it is truncated to just 0 every time. That multiplies the other side by zero and completely nullifies your answer every time.

    0 讨论(0)
  • 2020-11-22 07:45

    5 and 9 are of int type
    hence 5/9 will always result 0.

    You can use 5/9.0 or 5.0/9 or 5.0/9.0

    You can also check C program for converting Fahrenheit into Celsius

    0 讨论(0)
  • 2020-11-22 07:53

    write 5/9.0 instead of 5/9 -- this forces double division

    0 讨论(0)
  • 2020-11-22 07:56

    You need to use floating point arithmetic in order to perform these type of formulas with any accuracy. You can always convert the final result back to an integer, if needed.

    0 讨论(0)
  • 2020-11-22 08:04

    try celsius = ((double)5/9) * (fahrenheit-32); Or you can use 5.0.

    The fact is that "/" looks at the operand type. In case of int the result is also an int, so you have 0. When 5 is treated as double, then the division will be executed correctly.

    0 讨论(0)
提交回复
热议问题