简体   繁体   中英

Wrong element output in C#

I apologize in advance, but I'm fairly new to C# in this context (I've used it in Unity, but never on its own).

I'm trying to create a string array, and within a loop, have another array with, let's say, a rating system (int elements). Unfortunately, my problem seems on a level of its own.

This is the code:

using System;

public class Test
{
  public static void Main()
  {
    string [] arr1 = new string[] {"a","b","c","d","e"};
    int a = 0;
    foreach (var element in arr1)
    {          
        int [] myRate = new int [5] {1,2,3,4,5};
        int [] rating = myRate;
        a = rating[0];
        Console.WriteLine (element +": " + (rating[a]));
    } a++;
  }
}

My problem is the output is supposed to be 1 (for all elements because I'm still working on the incrementation), but this is the output:

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

I tried to reduce the code as much as possible to pinpoint the problem (that's why it's kind of minimalistic), but I still cannot figure it out. When I change the zero to 1 the output is 2, and so on. If I change it to 4 it says its out of bound. Your help is much appreciated, and thank you in advance.

Inside your loop, when do this:

a = rating[0];

then a becomes 1, because it's the first item in your int array. Then you write this to console:

rating[a]

...which results to this (since a is 1):

rating[1]

...and the second item in your array is 2, that's why you get this output.


Two ways of outputting 1:

foreach (var element in arr1)
{          
    int [] myRate = new int [5] {1,2,3,4,5};
    int [] rating = myRate;
    a = 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 a side note, you may consider creating the int[] outside your loop, since you are every iteration creating the same array, unless you actually intend to create arrays with different values every new iteration.

Because "a" contains number "1".

And number 1 on index of rating array is 2.

If you want to print number 1, you should start at index 0. Which is:

Console.WriteLine (element +": " + (rating[0]));

If you want 1 in answer then write:

Console.WriteLine (element +": " + a);

or

Console.WriteLine (element +": " + rating[0]);

because a=rating[0]; ie first element of array whose value is 1.

you are using:

Console.WriteLine (element +": " + (rating[a]));

ie rating[1] because value of a is 1 .

so rating[1] is second element of array whose value is 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM