我正在學習C#我正在寫一個程序,使數組填充50個隨機數字1-6像骰子,然後檢查每個值或「邊」出現的次數。我在本週早些時候在Python中做了一個骰子游戲,並且遇到了很多麻煩,所以我讓i = j =和match = print outs來測試循環和匹配是否正確迭代,所以我在這裏做了同樣的事情,並且注意到了一些邏輯錯誤:C#骰子游戲邏輯錯誤
i循環似乎重複罰款,但每1次迭代的i,J應該重複50次,但我只得到過一次。
i或j循環根本不會迭代,除非在第47行它指出j> dice.Length。寫作應該是j < dice.Length使它不會迭代。在屏幕上顯示的50個隨機數,所以我知道骰子是50的長度和j是0.
第三在第50行,如果骰[i] ==骰[j]我得到一個錯誤,j是無效的除非我在for循環之上聲明j,如果我這樣做,我不能在for循環中執行int j = 0,所以我放棄了for循環並做了一個while循環,但它仍然只爲第一個值添加一個值匹配,而不是下一個可能的49.
我只在靜態void編碼,因爲它是一個簡單的控制檯應用程序,感謝您的幫助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wk8hw2
{
class Program
{
static void Main(string[] args)
{//staticvoid
int size = 50;
int diceSides = 7;
int matchAdd = 0;
int[] dice = new int[size];
int[] match = new int[diceSides];
Random rnd = new Random();
int j = 0;
Console.WriteLine("Press any key to roll the dice " + size + " times.");
Console.ReadKey();
for (int i = 0; i < dice.Length; i++)//roll dice
{
dice[i] = rnd.Next(1, diceSides);
}
for (int i = 0; i < dice.Length; i++)//show dice
{
Console.Write(dice[i] + " ");
}
Console.WriteLine("done showing dice");//DEBUG
for (int i = 0; i < dice.Length; i++)//outer match loop
{
Console.Write("i = " + i);//DEBUG
if (match[dice[i]] == 0)//if not matched add to match array
{
Console.WriteLine("not yet matched");
matchAdd = 1;
}
else//if alerady matched add no more
{
Console.WriteLine("already matched");
matchAdd = 0;
}
j = 0;
while (j > dice.Length)//inner match loopSUPPOSED TRO BE LESS THAN
{
Console.WriteLine("j = " + j);
if (dice[i] == dice[j])//if equal add to match array
{
match[dice[i]] = match[dice[i]] + matchAdd;
Console.WriteLine("val " + match[dice[i]]);
}
j++;
}
}//endFORouter
for (int i = 1; i < match.Length; i++)
{
Console.WriteLine(i + " came up " + match[i] + " times.");
}
Console.ReadKey();
}//endstaticvoid
}
}
如果你在邏輯上滾動6面骰子,不要有一個值爲'7'的變量'diceSides'。使它成爲'6',因爲這是有道理的,並將滾動語句更改爲'rnd.Next(diceSides)+ 1'。 – itsme86
最終值爲6是不是問題,在C#顯然你輸入的最大值實際上是最大+ 1,如果我把6我只得到1-5,如果我輸入7爲最大我得到1- 6 – JGoss
但是,如果你像我建議的那樣做了'rnd.Next(6)+ 1',你可以以更清晰的方式得到(0-5)+ 1給你1 - 6,而不需要混淆讀者的想法,重新嘗試擲出7面骰子。 – itsme86