Why does this not calculate right?

This is a piece of code that I found that doesn't properly calculate the way it should. Why is this?

1
2
3
4
  double c = 20;
  double f;
  f = (9 / 5) * c + 32.0;
  cout << f;
(9 / 5) is integer division. Instead, use either (9.0 / 5), (9 / 5.0), or (9.0 / 5.0)
It is always a good practice to write "double" with the decimals.
Last edited on
So many problems beginners have which involve simple math calculations not coming out right in their C++ programs, seem to be attributable to this sort of "integer/double" mistake.

Ought to be the first thing checked.

(Fairness compels me to add that I'm still something of a beginner, myself. And I've fallen prey to this mistake a time or two.)
Topic archived. No new replies allowed.