arrays - Wrong element output in C# -


i apologize in advance, i'm new c# in context (i've used in unity, never on own).

i'm trying create string array, , within loop, have array with, let's say, rating system (int elements). unfortunately, problem seems on level of own.

this code:

using system;  public class test {   public static void main()   {     string [] arr1 = new string[] {"a","b","c","d","e"};     int = 0;     foreach (var element in arr1)     {                   int [] myrate = new int [5] {1,2,3,4,5};         int [] rating = myrate;         = rating[0];         console.writeline (element +": " + (rating[a]));     } a++;   } } 

my problem output supposed 1 (for elements because i'm still working on incrementation), output:

a: 2 b: 2 c: 2 d: 2 e: 2 

i tried reduce code as possible pinpoint problem (that's why it's kind of minimalistic), still cannot figure out. when change 0 1 output 2, , on. if change 4 says out of bound. appreciated, , thank in advance.

inside loop, when this:

a = rating[0]; 

then a becomes 1, because it's first item in int array. write console:

rating[a] 

...which results (since a 1):

rating[1] 

...and second item in array 2, that's why output.


two ways of outputting 1:

foreach (var element in arr1) {               int [] myrate = new int [5] {1,2,3,4,5};     int [] rating = myrate;     = 0;     console.writeline (element +": " + (rating[a])); } a++; 

and

foreach (var element in arr1) {               int [] myrate = new int [5] {1,2,3,4,5};     int [] rating = myrate;     console.writeline (element +": " + (rating[0])); } a++; 

as side note, may consider creating int[] outside loop, since every iteration creating same array, unless intend create arrays different values every new iteration.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -