C ++ Store twice in int variable

This is a small program that calculates spaces in the size of the "interval" that are between the two numbers from "to". Then I compute the "size" (number of spaces) and store it in an int variable, and sometimes give me a smaller value.

Here is the code:

double from=0, to=1, interval=0.1;

cout << "WORKING WITH VARIABLES: " << endl;
double operation = (to-from)/interval +1;
cout << "Size: " << operation << endl;

int size = operation;

cout << "Size after storing: " << size << endl << endl;

cout << "WORKING WITHOUT VARIABLES: " << endl;
cout << "Size: " << (to-from)/interval +1 << endl;

size = (to-from)/interval +1;

cout << "Size after storing: " << size << endl << endl;

The problem is how it stores the interval. If the interval = 1, everything is fine, but if it is 0.1, as in the example, it gives me 10 instead of 11 in the "Size after storage" of the second case.

I found out that it works well with an interval of 0.25 (2 ^ -2).

EDIT: I did not find that he fails in the first case, always in the second.

+4
source share
3

. 0,25 . 1/4, 0.01 . 0,1 - 1/10, . 1/16 + 1/32 +...

, 1/10 , 10 * 1/10 1.

, , - , , double.

+5

, . , , , 0.1, 10.999.... 11. double int , 10. int .

int size=operation+0.0000000001;
+4

If you want to convert doubleclose to an integer (due to rounding errors, as explained by others) to int, always round the value to the nearest integer, for example. c round(), before converting the value to int, since converting doubleto inttruncates the value and will give an incorrect result if the error is negative.

0
source

All Articles