我正在C#中的骰子模擬器上工作,我做while循環不像我所期望的那樣工作。我現在註釋掉了它,但沒有它,骰子模擬器方法的結果總是返回「2」(因爲do/while沒有檢查骰子的總數是否等於用戶輸入)。任何人都願意幫助新手修改代碼,以便程序正常工作嗎?雖然while循環不工作方法,使用隨機整數來模擬骰子滾動
非常感謝您的幫助!
//Begin Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int DiceRollSim(int input)
{
Random dice1 = new Random();
Random dice2 = new Random();
int sum = dice1.Next(1, 7) + dice2.Next(1, 7);
int count = 1;
/* do
{*/
{
sum = dice1.Next(1, 7) + dice2.Next(1, 7);
count++;
}
/* } while (sum != input);*/
return count;
}
static void Main(string[] args)
{
Console.WriteLine("Hello! This program rolls a pair of die until the sum of the die is equal to your given number.\n\n");
Console.WriteLine("Please enter a number between 2 and 12: ");
int num = int.Parse(Console.ReadLine());
int rolls = DiceRollSim(num);
int[] array_possiblesum = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
if (Array.IndexOf(array_possiblesum, num) > -1)
{
Console.WriteLine("\n\n Congratulations! It took " + rolls + " rolls of the die for them to equal your entry, " + num + ".");
}
else
{
Random newnum = new Random();
num = newnum.Next(2, 13);
int roll2 = DiceRollSim(num);
Console.WriteLine("\n\n I'm sorry! Your input was not valid so we chose a new number for you. The number we chose is:" + num+".");
Console.WriteLine(" \n\n It took " + roll2 + " rolls of the die for them to equal your entry, " + num + ".");
}
}
}
}
留意:當你在同一時間實例兩個隨機類,他們一般會給*同*「隨機」號碼清單。這意味着你只能滾動偶數。 –
當用戶輸入一個無效的號碼時,您的代碼無論如何都會調用DiceRollSim。 (以及如果一個邪惡用戶輸入「A」會怎麼樣?) –
如果你在循環中覆蓋它,那麼初始化'sum'有什麼意義?它是以前(可能)使用'while'循環的剩餘嗎? – kiziu