0

Image for the code in C++

In this code, why are the outputs for 1/2 and 0.5 different?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
gg-dev-05
  • 353
  • 8
  • 14
  • 7
    Please don't post images of code, least of all as links. Copy-paste code (or any text really) as *text* into the question. And please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Sep 28 '19 at 19:53
  • 3
    And the difference between `1 / 2` and `0.5` (or `1.0 / 2.0`) should have been taught by your text-book. If you don't have one then [here's a list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). You will save yourself a lot of time and problems if you invest in one or two. – Some programmer dude Sep 28 '19 at 19:55

1 Answers1

4

1 and 2 are integers, and use integer based division (1/2=0) You want to use 1.0 / 2.0 (resulting in 0.5)

J. Murray
  • 1,460
  • 11
  • 19