用C#编写程序模拟两个骰子。用Random类对象投第一个骰子,并再次用Random类投第二个骰子,计算两值的和。

说明,由于每个骰子显示的1-6的整数值,因此两个骰子的和为2-12,7最常见,2和12最不常见。程序将投两个骰子36000次,用一维数组估算每个和出现的次数,用表格形式显示结果。

using System;

namespace csharpconsole
{
class Program
{
static void Main(string[] args)
{
int total = 36000;
int[] count = new int[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Random r = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < total; i++)
{
int x1 = r.Next(1,7);
int x2 = r.Next(1, 7);
int sum = x1 + x2;
count[sum - 2]++;
}

Console.WriteLine("点数和\t出现比率");
for (int i = 0; i < 11; i++)
{
double rate = ((double)count[i]) / ((double)total);
rate *= 100;
Console.WriteLine(string.Format("{0}\t{1}%", i+2, rate.ToString(".00")));
}
Console.ReadKey();
}
}
}
温馨提示:答案为网友推荐,仅供参考