I want to ask why this code is not running... I tried using float data type it didn't work | Sololearn: Learn to code for FREE!

+2

I want to ask why this code is not running... I tried using float data type it didn't work

using System; namespace Project { class MyClass { public static void Main(string[] args) { double[] numbers = new double[3]; numbers [0] = 4.5; numbers [1] = 52.567; numbers [2] = 17.233; numbers [3] = 8.725; Console.WriteLine(numbers[2]); Console.ReadKey(); } } }

10/20/2021 12:58:47 PM

omitogun toni

8 Answers

New Answer

+2

When you defined <numbers> array, you allocated 3 slots for it. But you tried to fill it with 4 values, from index 0 up to index 3. Array with 3 slots can only store elements from index 0 up to index 2.

+1

Ooh thanks i see my mistake now... Thank you very much Ipang

+1

Can you pls tell me why this is not running... Console is telling me "cannot implicitly convert int to double".

+1

Problem is in the for...loop initialization, where you defined <i> as double, and in loop condition part you compare <i> against <numbers.Length> which is an integer. I strongly recommend you to never use floating point value for loop iteration counters. Floating point type is not finite as it is integers. We are safer to use integer for loop iteration counter ...

+1

No brother, you misunderstood me. Loops are useful and closely related with data collections like array. It is so closely related. I was saying that we shouldn't use floating point type (`float`, `double`) as data type of the loop iteration counter variable. Look here ... for( int i = 0; i < 5; i++ ) Here <i> is a variable we use as iteration counter, for this counter, we must use integral types (whole numbers) because their value are finite. Floating point types like `float` and `double` supports fractional, and the fractional part makes it uneasy to do a precise comparison e.g in the loop condition.

+1

Ooh okk i understand thanks Ipang

0

using System; namespace Project { class MyClass { public static void Main(string[] args) { double[] numbers = new double[5]; numbers [0] = 4.5; numbers [1] = 52.567; numbers [2] = 17.233; numbers [3] = 8.725; for (double i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } Console.ReadKey(); } } }

0

Ooh ok so there is no loop of any form in arrays for float and double I really really appreciate Ipang... Thank you