【发布时间】:2021-01-07 15:53:27
【问题描述】:
所以我是编码初学者(1 个月)。 我已经更改代码 4 天了,没有运气。 我坚持让我的 randomNumber == winNum 中断。 如果用户写入,用户将获得 10 个数字(假设 winNum 为 9) 1,2,5,9,10,11.... 等等。代码不会选择数组中的数字,并打印“你幸运”。 该代码用于工作。 9.2.3.4.5 ......等等,它得到“你很幸运”,但不再是。 我也得到“你输了”“你输了”“你输了”和“游戏结束”。
不确定我做错了什么。
static void Main(string[] args)
{
// -int size = Convert.ToInt32(Console.In.ReadLine()); // this to change amount of variables the user wants instead of [x]
int[] numbers = new int[10]; // task 1, modul 3. The 10 in the array is a statment for how many varibles this array can hold.
// you can have as many varibles as you want.
Random randomNumbers = new Random();
int winNum = randomNumbers.Next(1, 26);
Console.WriteLine(winNum);
Console.WriteLine("Pick your 10 numbers! "); // här får vi våra 10 tal av användaren
for (int hallon = 0; hallon < 10; hallon++) //this loop will print the users numbers
{
Console.WriteLine($"Your have used: {hallon}" ); // här får vi våra 10 tal av användaren
try
{
numbers[hallon] = Convert.ToInt32(Console.In.ReadLine()); // numbers lagrar våra 10 tal som kommer spelas nu mot winNum
}
catch (SystemException e) // going to catch if the user writes in a letter instead of a number
{
--hallon;
Console.WriteLine(e.Message);
}
if (numbers[hallon] < 1 || numbers[hallon] > 25)
{
Console.WriteLine("Write a number within 1-25. ");
--hallon;
}
}
for (int hallon = 0; hallon < 10; hallon++)
{
if (numbers[hallon] == winNum) // vad gör jag om jag vill ha två vinnande resultat?
{
Console.WriteLine("Lucky number:" + numbers[hallon]);
break;
} ////task 2 modul 3 this loops my array untill i have all varbiles printed
}
for (int hallon = 0; hallon < 10; hallon++)
{
if (numbers[hallon] != winNum)
Console.WriteLine("You lost");
}
Console.WriteLine("End of the game");
Console.ReadLine();
}
}
【问题讨论】:
-
学习how to debug small programs对于程序员来说是一项极其宝贵的技能。请浏览链接页面并将其中描述的技术应用于您的问题,以缩小错误原因。
-
正如 vc 所发现的 - 您的缩进已关闭,因此在第一个“for”循环中发生了很多事情。最后同一行的两个 } 暗示了这一点。尝试修复缩进(有一些工具可以为你做这件事),它可能会让事情变得更干净。与python不同,C#中的缩进只是为了方便程序员,它对编译器没有影响
-
我一直在使用 Visual Studios 的调试工具,但是(程序运行时没有任何错误)”所以代码在技术上是“错误的”。但它并没有做我想做的事。但我 appricaite 你的反馈--PranavHosangadi。 @StuartMoore我知道我最后的“for循环”是“错误的”,或者甚至可能不需要,正如micke在他的解释中所写的那样。我知道在其他软件中缩进作为 python 有不同的功能,我会尝试让我的代码更干净,并停止使用不必要的代码。正如我之前所说。感谢您抽出宝贵的时间!。