What is the difference?

Jan 21, 2014 at 10:54am
what is difference?
1) c = (f-32)*5/9; // result OK.
2) c = ((f-32)*5)/9; // result OK
3) c = ((f-32)*(5/9)); result is 0

Why c (result) is always 0 in case of 3)?
Jan 21, 2014 at 10:57am
In integer arithmetic, what do you think (5/9) will evaluate to?
Jan 21, 2014 at 10:59am
i have defined c & f as float.
once c & f both defined as a float whole expression must be evaluated as a float.
all scientific calculators performs OK with any of three expressions regardless of parentheses.

once c & f both defined as a float, the compiler must treat whole expression as float.
Last edited on Jan 21, 2014 at 11:03am
Jan 21, 2014 at 11:00am
And where in (5/9) do you see either c or f?

5 is an integer. 9 is an integer. So (5/9) is integer arithmetic.
Jan 21, 2014 at 11:07am
if C or C++ compilers fails to evaluate the value of (5/9) properly, I would not agree to other short-cuts.
How come any scientific calculator evaluates all three expressions perfectly?
Jan 21, 2014 at 11:28am
C and C++ is perfectly capable of evaluating whatever mathematical algorithms you give it. The onus is on you, as the developer, to use the language correctly to express the algorithm you want.

Scientific calculators presumably do not distinguish between integer values and floating-point values. C and C++, however, are strongly typed languages. If you use integers, then the language will treat them as integers. In the case of 5/9, it will evaluate the result as an integer. If you use 5.0/9.0, it will evaluate the result as a float.

There are clear, deterministic rules for how the language treats different types of quantity, and how it treats situations where mixed types are used. If you're going to use the language, you'd do well to learn that.

One very important thing to understand about C and C++ is:

Types are important.
Last edited on Jan 21, 2014 at 11:29am
Jan 21, 2014 at 12:18pm
as you said,
c = ((f-32)*(5.0/9.0)); // works OK.

I am a newbie, just finished two class an intro to C/C++, and just basics of C++ program.

#include <iostream>

int main ()
{
cout << "Hello World!";
cout << "I'm a newbie to C++";
}

It is just a start of a long long journey.
Thanx!
Jan 21, 2014 at 12:21pm
You're welcome.
Topic archived. No new replies allowed.