【发布时间】:2022-01-07 08:23:26
【问题描述】:
我是 c# 的初学者,所以我试图制作一个程序,为你和敌人掷骰子 10 回合,每回合将你的掷骰数加到总计数中,谁得到最大最后赢了,我没有一路完成,但这是我目前所拥有的:
namespace dfgs
{
class dice
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 11)
{
Console.WriteLine("Player Roll Is" + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is" + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd;
aisc = aisc + airnd;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
Console.ReadLine();
}
}
}
}
每当我尝试编译时,我都会收到错误Operator +' cannot be applied to operands of type int' and System.Random',此错误出现两次,我尝试将随机数的类型更改为 int 但随后我收到错误消息Type int' does not contain a definition for Next' and no extension method Next' of type int' could be found. Are you missing an assembly reference? 我有点卡在这里,任何帮助将不胜感激。
编辑:感谢所有回答的人,我已经成功完成了这项工作,这是最终代码,它不是最干净的,但可以按预期工作:
namespace dfgs
{
class die
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 10)
{
Console.WriteLine("Player Roll Is " + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is " + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd.Next(6);
aisc = aisc + airnd.Next(6);
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
else{
break;
}
if (turns == 10){
if (plsc > aisc){
Console.WriteLine("The Player Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
else if (aisc > plsc){
Console.WriteLine("The AI Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
break;
}
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
您忘记在
plrnd和airnd之后放置.Next()位 -
您真的不需要多个
Random实例。使用相同的实例来获取所有随机数。正如您设置的那样,plrnd和airnd可能会发出相同的随机数序列(这可能不是您想要的)。另一个专业提示:将这些变量称为playerRandom(或playerRand或playerRng(其中 RNG 是随机数生成器))只需要一些额外的击键,但会让您的代码在下次查看时更有意义在它:“我想知道我所说的 air-ND 是什么意思” -
搜索标题结果this post