double array yields only zeroes

PPopulus9/10/2022
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?
Mmtreit9/10/2022
integer math
Mmtreit9/10/2022
Dividing two integers truncates the fractional part
Mmtreit9/10/2022
Cast the integers to double
PPopulus9/10/2022
Doesn't "Convert.ToDouble()" do that?
AAuger9/10/2022
That parses a double from a string
AAuger9/10/2022
casting is very different
Mmtreit9/10/2022
Um...then it wouldn't compile
AAuger9/10/2022
Oh, good point
AAuger9/10/2022
I don't use that Convert class too often. I suppose it's an overload then
Mmtreit9/10/2022
But the convert is on the result of the integer division where truncation has already happened
PPopulus9/10/2022
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?
Mmtreit9/10/2022
You need to do floating point division
Mmtreit9/10/2022
Like 1 / (double)ints[i]
PPopulus9/10/2022
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?
Mmtreit9/10/2022
No
Mmtreit9/10/2022
But you don't need to use Convert here
Mmtreit9/10/2022
You need to convert int to double before you do the division, not after
Mmtreit9/10/2022
You could use Convert to do that technically but casting is more straightforward
PPopulus9/10/2022
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.
PPopulus9/10/2022
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.
Mmtreit9/10/2022
Convert takes as input the result of the division (in your example) AFTER the integer division happened and already threw away the decimal part
Mmtreit9/10/2022
When you divide two integers the result is an integer, and integers have no way to represent fractions