On Apr 13, 4:53 pm, Topi Linkala <n...@iki.fi> wrote:
> Joe Wright wrote:
> > Topi Linkala wrote:
>
> >> Robert Gamble wrote:
>
> >>> On Apr 13, 3:33 pm, Topi Linkala <n...@iki.fi> wrote:
>
> >>>> Question 3.15:
>
> >>>> Why does the code
>
> >>>> double degC, degF;
> >>>> degC = 5 / 9 * (degF - 32);
>
> >>>> keep giving me 0?
>
> >>>> Would the following rearrangement solve the problem?
>
> >>>> degC = 5 * (degF - 32) / 9;
>
> >>> Did you read the answer to the question (<http://c-faq.com/expr/
> >>> truncation1.html>)?
>
> >> Yes I read and it says:
>
> >> "If both operands of a binary operator are integers, C performs an
> >> integer operation,..."
>
> >> But in my rewriting there are no binary operation with integer values.
> >> That's why I'm asking if it would work.
>
> >> Topi
>
> > The statement..
>
> > degC = 5 / 9 * (degF - 32);
>
> > ..can't work because 5 / 9 is (int) zero. Also degF is not initialized.
>
> > degC = (degF - 32) * 5 / 9;
>
> > should work better for you.
>
> I don't think so because there's no reason to believe that the
> multiplication is done before the division, but in my example that
> doesn't matter as one of the operands is double in any case.
Actually, the multiplication is guaranteed to be performed before the
division because they both have the same precedence and are left-to-
right associative.
--
Robert Gamble