C# 如何将数组中的整数实例存储在C中的单独变量中? 描述
我正在尝试制作一个C程序,从1到6中选择一个随机数,并将其存储在一个数组中。我应该如何存储它:作为数字1到6的实例,还是作为完整序列 密码C# 如何将数组中的整数实例存储在C中的单独变量中? 描述,c#,random,C#,Random,我正在尝试制作一个C程序,从1到6中选择一个随机数,并将其存储在一个数组中。我应该如何存储它:作为数字1到6的实例,还是作为完整序列 密码 感谢@PeterSmith和@Martheen解决了评论中的问题:数组instanceCount可以用来存储实例的数量,而不是整个序列。这是生成的代码 using System; namespace DiceProbabilityCalc { class Program { static void Main(string[]
感谢@PeterSmith和@Martheen解决了评论中的问题:数组instanceCount可以用来存储实例的数量,而不是整个序列。这是生成的代码
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}
你能澄清一下你的问题吗?我认为instanceCount应该是一个数组,或者可能是一个字典,以减少索引/键编号1到6的混淆,其值是这些数字出现的次数。您确实需要存储完整的序列吗?请尝试将instanceCount的大小设置为不同随机数的数目6,然后增加每个序列的instanceCounthit@PeterSmith,谢谢你的建议。“试试看。”马丁,谢谢你的建议。提示:当你创建一个数组时,所有的位置都用默认值初始化,默认值为0integers@HansKesting,谢谢。我已经编辑了答案。
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}