-2

I don't understand how C++ cannot make simple calculations like a simple calculator. I have code producing wrong results with double division and multiplication. An example:

#include <iostream>
int main()
{
    double a = 0.00001;
    int b = 1/a;
    std::cout <<b<<std::endl;
    return 0;
}

This gives 99999 when it's supposed to give 100000. How can I have the right result?

Windows 7 64 bit, MSVC2012

Edit: Thank you for the explanation. I deduct that to solve my problem I have to round it before casting to int. I wonder if this is the default way of doing it as this kind of error doesn't seem acceptable to any program based on decimal calculations.

user3023605
  • 459
  • 5
  • 11

1 Answers1

2
double a = 0.00001;

Floating point numbers like 0.00001 cannot be represented precisely using double. a is actually a little bit bigger than 0.00001. 1/a therefore, is a little smaller than 100000, casting it to int truncated to 99999.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • So the answer is to avoid casting to int? – user3023605 Oct 15 '14 at 10:26
  • @user3023605 Casting `1.99` to `int` would result as `1`. A better alternative is to use a round function. – Yu Hao Oct 15 '14 at 10:29
  • 1
    No, rounding is not a good option. The "right" solution is to use a decimal data type that can represent the values exactly. – David Heffernan Oct 15 '14 at 10:42
  • 1
    @DavidHeffernan I know it's not "right", but better in practice comparing to casting. You are absolutely right. – Yu Hao Oct 15 '14 at 10:49
  • 1
    @DavidHeffernan The question uses `double`, a compact representation on 64 bits with, in most processors, hardware-accelerated basic operations and, on most operating systems, excellent implementations for elementary functions. There is absolutely no indication in the question that a decimal datatype with none of these advantages is an acceptable trade-off. – Pascal Cuoq Oct 15 '14 at 12:16
  • @PascalCuoq It depends entirely on the application, a critical fact that you have completely neglected to consider. – David Heffernan Oct 15 '14 at 12:18
  • @DavidHeffernan Did I say something akin to “No, rounding is not a good option. The "right" solution is …”? – Pascal Cuoq Oct 15 '14 at 13:04
  • @PascalCuoq The asker said "program based on decimal calculations" which seems quite clear to me. – David Heffernan Oct 15 '14 at 13:05