0

I am new to C++ and when writing a program, I've found that two equivalent expressions are returning different values when I call the floor function. I assume that it has something to do with how the computer stores values after performing mathematical operations but I'm not completely sure. I've written the two expressions below and was wondering if there is any way to work around this (i.e. get the first floor call to return 1 rather than 0 without using ceil).?

cout << floor((((((3661. / 3600.) - 1) * 60.) - 1) * 60.)) << endl; // returns 0
cout << floor((1. / 60.) * 60.) << endl; // returns 1
  • 2
    More good reading: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/800-7895/800-7895.pdf) – user4581301 Apr 02 '22 at 00:41
  • Also you can use a library in c++ for this, for example [GNU GMP](https://gmplib.org/). Also some languages have fractional types built in, ex: clojure. – ATOMP Apr 02 '22 at 00:47
  • Floating-point types are **not** like real numbers. The intuition you've developed over the years about how mathematical operations work will often lead you astray when you're dealing with floating point. – Pete Becker Apr 02 '22 at 13:45

0 Answers0