我正在尝试编写一个我认为必须使用递归的程序。简而言之:创建一个掷骰子的程序。如果它落在6上,就会创建并滚动两个骰子,依此类推,直到不超过6个。
问题不是创建一个新的或真正的随机对象,而是递归骰子。
递归方法如下所示:
public static int Recursion(int a)
{
Random m = new Random();
if (a < 6)
{
return a;
}
else
{
a = m.Next(1, 7);
return Recursion(a) * 2;
}
}
发布于 2019-05-13 01:26:59
可能是这样的吗?
public static int Roll() {
return Roll(new Random(), 1);
}
public static int Roll(Random random, int diceCount) {
int sum = 0;
for (int dice = 1; dice <= diceCount; ++dice) {
int rolled = random.Next(1, 7);
if (rolled == 6) {
sum += Roll(random, 2)
}
else
{
sum += rolled;
}
}
return sum;
}
所以,首先我掷一个骰子。如果它不是6,那么我接受它的值作为结果。如果是六个,那么我移走骰子,并用另外两个我掷骰子来代替它。然后,对于每一个新的骰子,我遵循相同的规则,直到桌子上的所有骰子都掷完了,没有一个是6,现在我将骰子的所有值相加。这就是这个递归算法的作用。请注意,无论它有无限低的机会,你可以玩到时间结束,因为总是有机会滚动6,所以你可能只滚动6直到你死。
发布于 2019-05-13 01:29:59
您可以通过创建骰子对象使其更面向对象:
using System;
using System.Collections.Generic;
class Dices
{
public class Dice
{
private static Random roler = new Random();
private int roledNumber;
public int Role()
{
roledNumber = roler.Next(6) + 1 ;
return roledNumber;
}
public int Number
{
get { return roledNumber; }
}
}
static void Main(string[] args)
{
List<Dice> allDices = new List<Dice>();
Dice firstDice = new Dice();
allDices.Add(firstDice);
if (firstDice.Role() == 6) createDices(allDices);
}
static void createDices(List<Dice> dices)
{
Dice first = new Dice();
dices.Add(first);
if (first.Role() == 6) createDices(dices);
Dice second = new Dice();
dices.Add(second);
if (second.Role() == 6) createDices(dices);
}
}
https://stackoverflow.com/questions/56101393
复制相似问题