那么在 C# 中创建一个循环的一个好的、简单的算法是什么,每次某个值出现在一个数组中时,它会将 1 加到另一个数组中的计数器上?
例如我有这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication22
{
class Program
{
const int SIZE = 12;
static void Main(string[] args)
{
int[] numbers = new int[SIZE] {5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1};
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] {15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44};
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
int[] Count = new int[4];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Count[x]++;
}
}
for (i = 0; i < 4; i++)
{
Console.WriteLine("{0}", Count[4]);
}
}
}
}
我只计算 4 个数字出现在 numbers 数组中的次数。有人建议我在第一个循环中使用该方法,但它似乎不起作用,并创建一个索引超出数组范围的错误。我想显示每个数字(5、7,9 和 1)出现在 4 行中的次数。
编辑:不使用 LINQ 或任何其他花哨的东西,如 Dictionary 或其他任何东西。