I have an integer array of dimension n, say now n=9.
I would like to initialize it to
[0.11,0.11,0.11,0.11,0.11,0.11,0.11,0.11,0.12]
Where each entry is 1/n, and take up to two decimals,
and the last entry is the remaining number from 1.
How should I do this easily? Here’s what I do now
double sumOfn=0;
for (int i = 0; i < array.Length;i++ )
{
double n;
if (i < array.Length-1)
{
array[i] = Math.Floor((1/(double) array.Length)*100/100);
sumOfn += n;
}else
{
array[i] = 1 - sumOfn;
}
}
You can’t constraint a double to a specific precision when you compute a value.
What I would recommend is doing an integer division of 100 per n then divide that value by 100.
The last value can be easily computed by adding the rest of the division to the last element before dividing it by 100.
This is basically an euclidean division as we did in school when we first learned floating point 🙂