Why does division result in zero instead of a decimal?

前端 未结 5 626
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 05:38

Teaching myself C and finding that when I do an equation for a temp conversion it won\'t work unless I change the fraction to a decimal. ie,

tempC=(.555*(tempF

相关标签:
5条回答
  • 2020-11-21 06:01

    When you do 5/9, 5 and 9 are both integers and integer division happens. The result of integer division is an integer and it is the quotient of the two operands. So, the quotient in case of 5/9 is 0 and since you multiply by 0, tempC comes out to be 0. In order to not have integer division, atleast one of the two operands must be float.

    E.g. if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.

    0 讨论(0)
  • 2020-11-21 06:11

    5/9 is an integer division not a floating point division. That's why you are getting wrong result.

    Make 5 or 9 floating point variable and you will get correct answer.

    Like 5.0/9 OR 5/9.0

    0 讨论(0)
  • 2020-11-21 06:13

    If you put 5/9 in parenthesis, this will be calculated first, and since those are two integers, it will be done by integer division and the result will be 0, before the rest of the expression is evaluated.

    You can rearrange your expression so that the conversion to float occurs first:

    tempC=((5/9)*(tempF-32));tempC=(5*(tempF-32))/9;

    or of course, as the others say, use floating point constants.

    0 讨论(0)
  • 2020-11-21 06:20

    It looks like you have integer division in the second case:

    tempC=((5/9)*(tempF-32))
    

    The 5 / 9 will get truncated to zero.

    To fix that, you need to make one of them a floating-point type:

    tempC=((5./9.)*(tempF-32))
    
    0 讨论(0)
  • 2020-11-21 06:20

    5/9 is an integer expression, as such it gets truncated to 0. your compiler should warn you about this, else you should look into enabling warnings.

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