+ 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(); } } }

20th Oct 2021, 12:58 PM
omitogun toni
omitogun toni - avatar
8 Antworten
+ 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.
20th Oct 2021, 1:17 PM
Ipang
+ 1
Ooh thanks i see my mistake now... Thank you very much Ipang
20th Oct 2021, 1:23 PM
omitogun toni
omitogun toni - avatar
+ 1
Can you pls tell me why this is not running... Console is telling me "cannot implicitly convert int to double".
20th Oct 2021, 1:27 PM
omitogun toni
omitogun toni - avatar
+ 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 ...
20th Oct 2021, 1:41 PM
Ipang
+ 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.
20th Oct 2021, 1:56 PM
Ipang
+ 1
Ooh okk i understand thanks Ipang
20th Oct 2021, 2:11 PM
omitogun toni
omitogun toni - avatar
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(); } } }
20th Oct 2021, 1:26 PM
omitogun toni
omitogun toni - avatar
0
Ooh ok so there is no loop of any form in arrays for float and double I really really appreciate Ipang... Thank you
20th Oct 2021, 1:44 PM
omitogun toni
omitogun toni - avatar