C
C#3y ago
populus

double array yields only zeroes

static void RunExerciseSixteen()
{
int[] ints = new int[10];
Random rnd = new Random();
double[] dbls = new double[ints.Length];

for (int i = 0; i < ints.Length; i++)
{
ints[i] = rnd.Next(1, 500);
}

for (int i = 0; i < dbls.Length; i++)
{
Convert.ToDouble(dbls[i] = 1 / ints[i]);
}

foreach (int i in ints)
{
Console.WriteLine("Intsarray: " + i);
}
foreach (double i in dbls)
{
Console.WriteLine("Dblsarray: " + i); // Yields '0' repeatedly, why?
}
}
static void RunExerciseSixteen()
{
int[] ints = new int[10];
Random rnd = new Random();
double[] dbls = new double[ints.Length];

for (int i = 0; i < ints.Length; i++)
{
ints[i] = rnd.Next(1, 500);
}

for (int i = 0; i < dbls.Length; i++)
{
Convert.ToDouble(dbls[i] = 1 / ints[i]);
}

foreach (int i in ints)
{
Console.WriteLine("Intsarray: " + i);
}
foreach (double i in dbls)
{
Console.WriteLine("Dblsarray: " + i); // Yields '0' repeatedly, why?
}
}
What am I getting wrong here?
12 Replies
mtreit
mtreit3y ago
integer math Dividing two integers truncates the fractional part Cast the integers to double
populus
populusOP3y ago
Doesn't "Convert.ToDouble()" do that?
Auger
Auger3y ago
That parses a double from a string casting is very different
mtreit
mtreit3y ago
Um...then it wouldn't compile
Auger
Auger3y ago
Oh, good point I don't use that Convert class too often. I suppose it's an overload then
mtreit
mtreit3y ago
But the convert is on the result of the integer division where truncation has already happened
populus
populusOP3y ago
I haven't been taught casting yet. But from what I've read online it's putting the desired type in parenthesis before the variable I want casted, correct? Is there anything else I ought to know about casting?
mtreit
mtreit3y ago
You need to do floating point division Like 1 / (double)ints[i]
populus
populusOP3y ago
Ok, so what I've gathered from this is that the Convert class only deals in converting string to ints/doubles etc while (casting) converts types into other types?
mtreit
mtreit3y ago
No But you don't need to use Convert here You need to convert int to double before you do the division, not after You could use Convert to do that technically but casting is more straightforward
populus
populusOP3y ago
The casting works fine. I don't understand why however. Seems like I was doing the same thing with the Convert class. I'll be googling on the differences in a second. It seems to be a quite complex topic, one I won't be able to wrap my head around in this short moment. But I'd like to thank you for your help.
mtreit
mtreit3y ago
Convert takes as input the result of the division (in your example) AFTER the integer division happened and already threw away the decimal part When you divide two integers the result is an integer, and integers have no way to represent fractions
Want results from more Discord servers?
Add your server