'C programming double and int additions [closed]
My question is, how do I increment an array of doubles without it being 0.98999999? I'm currently doing a question on leetcode and I'm trying to this:
array[*level]++;
printf("This is array %lf", array[*level]);
where *level is a pointer to integer.
I kept trying array[*level]++;
or array[*level] += 1.00;
, but when I check the current double in the array using print, why does it always return 0.988889999 or something that's not 1.000000?
EDIT: I solved the leetcode question, but I'm still curious about this ^
2nd EDIT: I used a for loop to ensure every single index is exactly a 0 like this:
for (int j = 0; j < *returnSize; j++)
{
nodecount[j] = 0;
}
3rd EDIT
This is what I'm seeing in the leetcode stdout : ACTUAL:
[5.00001, 14.00003,1.00001]
EXPECTED:
[5.00000, 14.00000,1.00000]
How I got my answer, basically I used 5.00000 divided by 0.9899999 and 28.00000 divided by 1.9999989. Thus, routing back to the original question of why the divider became 0.9899999 instead of 1.000000
FINAL EDIT: THANKS FOR ANSWERING EVERYONE! Basically it was because did not initialise it EXACTLY 0 before incrementing
Solution 1:[1]
I kept trying
array[*level]++;
orarray[*level] += 1.00;
, but when I check the current double in the array using print, why does it always return 0.988889999 or something that's not 1.000000?
Because the value before the increment was not exactly 0.0. You have not given us enough information to evaluate why that might be.
Assuming IEEE-754 floating-point arithmetic (which is a pretty safe assumption), floating-point additions where the operands and the mathematical result are all exactly representable in the floating point format produce a representation of the exact result.
If you expect the elements of your array always to have integer values, then you probably should use an integer element type. If you chose double
for its range of representable values then you may have shot yourself in the foot, because the increased range relative to integer types comes at the cost of limited precision. If you need to represent exact integers larger than unsigned long long int
can represent then you need an arbitrary-precision math library such as GMP.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |