一直在研究数组,并在书中给出了以下示例
但无法弄清楚某些部分并需要一些帮助;
问题1
无法弄清楚这句话的作用:
Count[RandomArray[i]-1]++;
问题2
Console.Write("{0,2} Adet {1,2} >>>>", Count[i], i+1)
增加i ++时发生了什么
事先得到许多人的帮助..
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] RandomArray = new int[5];
for (int i = 0; i < 5; ++i)
{
RandomArray[i] = rnd.Next(1, 5);
}
int[] Count = new int[5];
for (int i = 0; i < 5; ++i)
{
Count[RandomArray[i]-1]++;
}
for (int i = 0; i < 5; ++i)
{
Console.Write("{0,2} Adet {1,2} >>>>", Count[i], i+1);
for (int j = 0; j < Count[i]; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
答案 0 :(得分:1)
{1,2,3,4,5}
之内。所以我们将制作5个长度数组。然后我们将只存储{{1 } {stat} number
索引。(number-1)
的统计信息
是我们的array[index]
统计数据现在使用100次尝试的相同代码:
number //number=(index+1)
当将这些视觉化为直方图时,我们将使用(索引+ 1)获取我们的数字的统计数据。
//make randomized 100 tries with {1,2,3,4,5} numbers
Random rnd = new Random();
int[] RandomArray = new int[100];
for (int i = 0; i < 100; ++i)
RandomArray[i] = rnd.Next(1, 6); //
//Now lets count of occurance of each number
int[] Count = new int[5];
for (int i = 0; i < 100; ++i){
// Count[RandomArray[i]-1]++;
int number=RandomArray[i];//get our number from randomized box
int index=number-1; // number stats will store at (number-1) index
//in our case we will increase our number count
++Count[index] ;//Count[index]+=1
}
答案 1 :(得分:0)
基本上,你首先要制作一个数组(RandomArray),里面填充1到5之间的一些随机数。
Random rnd = new Random();
int[] RandomArray = new int[5];
for (int i = 0; i < 5; ++i)
{
RandomArray[i] = rnd.Next(1, 5);
}
在这种情况下,++ i和i ++也会这样做
实际上,我的意思是在取值之前首先加1,而i ++意味着取i的值并加1。但正如我所说,这在这里没有什么不同
然后你将创建一个新数组(Count),你将计算这些随机数 因为随机数在1到5之间,你需要从数字中减去1,否则你将有OutOfBound Exceptions。
int[] Count = new int[5];
for (int i = 0; i < 5; ++i)
{
Count[RandomArray[i]-1]++;
}
之后,您将打印结果作为直方图,每个计算的数字使用*。 以前,您必须使用i-1来防止OutOfBounds异常。这意味着数字1的计数存储在索引0下,因此添加1添加结尾以显示正确的结果
for (int i = 0; i < 5; ++i)
{
Console.Write("{0,2} Adet {1,2} >>>>", Count[i], i+1);
for (int j = 0; j < Count[i]; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
示例强>
RandomArray = [1, 3, 4, 1, 5];
Count = [2, 0, 1, 1, 1];
2 Adet 1 >>>> **
0 Adet 2 >>>>
1 Adet 3 >>>> *
1 Adet 4 >>>> *
1 Adet 5 >>>> *
答案 2 :(得分:0)
//Say RandomArray comes {4,3,1,1,3}
for (int i = 0; i < 5; ++i)
{
Count[RandomArray[i] - 1]++;
//When i=0
// RandomArray[i]=4
//Count[RandomArray[i] - 1] will be Count[4-1] which will be Count[3]
//++ increment the value by 1. initially all values are 0 for Count Array
//so Count[3] will be 0++ which is equal to 1
//so Count[3]=1
//and so on for other indices.
}
for (int i = 0; i < 5; ++i)
{
//Here 0 format specifier is giving value of Count[i]
//1 format specifier is giving value of Count[i]
//2 is doing nothing since there is not corresponding parameter
Console.Write("{0,2} Adet {1,2} >>>>", Count[i], i + 1);
for (int j = 0; j < Count[i]; j++)
{
Console.Write("*");
}
Console.WriteLine();
}