Maths precedences

Sorry if this is a pretty basic (??) question but I am a newbie to C++.

If in C++ I use the expression c=(f-32)*5/9 and input f as 100 I get the expected 37 (using integers).

But if I use c=(f-32)*(5/9) I get 0 returned.

I have tried it in Basic and both work as expected and return 37. Is there something about precedences in C++ that is different
closed account (z05DSL3A)
5/9 = 0 with integers so multiplying (f-32) by that will also give you 0.
Thanks Grey Wolf - believe it or not I was just about to post to say that I had suddenly realised that but then I tried changing c and f to floats rather than ints and got the same result ie 0 for the latter expression.

I also tried defining a float con=5/9 and using the expression c=(f-32)*con (with c and f defined as floats as well) but that still gives 0.
closed account (z05DSL3A)
You would need to use a 'float' literal in your calculation of float con=5/9, so it would be float con=5.0/9.0. You can just have one as a float, that would still do in float division.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main(void)
{
    int temp_f = 100;
    int temp_c = (int) (temp_f - 32) * (5.0 / 9.0);
    
    std::cout << temp_c << std::endl;
    
    return 0;
}
Last edited on
Thanks again - I think I have sussed it - Takes a while but I get there in the end!!

It now works if I use (5.0/9.0) so it would appear that if you want to use a float it has to be expressed as 5.0/9.0 rather than 5/9.

So when I said "float con=5/9" that was making con equal to 0 as well.

Probably a valuable lesson learned there.
closed account (z05DSL3A)
So when I said "float con=5/9" that was making con equal to 0 as well.

Yes, 5 and 9 are integer literals so it would do an integer division and assign that result to the float variable.
Topic archived. No new replies allowed.