gpt4 book ai didi

c# - 猜谜和数字比较

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:16 26 4
gpt4 key购买 nike

我不明白如何将文件中的数字与函数传递的数字进行比较。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Guess_Game
{
class Program
{
static void Main(string[] args)
{
int quantity;
int min, max;
Console.WriteLine("Enter the Quantity of Numbers : ");
quantity = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the Maximum and Minimum Number that you wish to be in your file : \n");
Console.WriteLine("MIN : ");
min = int.Parse(Console.ReadLine());
Console.WriteLine("MAX : ");
max = int.Parse(Console.ReadLine());
Console.WriteLine("Now, Guess the Number : ");
int number = int.Parse(Console.ReadLine());

Console.WriteLine("Now Guess a Number That already contains in a File : ");
number = int.Parse(Console.ReadLine());
GuessGame(min, max, quantity, number);

//if(number!= // number not equal to that number that contains in a file.. how to write it in that
//if condition..
}

static void GuessGame(int min,int max,int quantity,int number)
{
Random r = new Random();
StreamWriter sw = new StreamWriter(@"D:\nasir\Guess Game\Guess Game\bin\Debug\ Guess Game.txt");

for (int i = 0; i < quantity; i++)
{
int temp = r.Next(min, max);
sw.WriteLine(temp);
}
// while(number != sw.WriteLine())
{
Console.WriteLine("Your Guess is Wrong!");
}
sw.Close();
}
}
}

最佳答案

您每次都在掷骰子(不公平,IMO)并且不读取该文件,而只是写入它。让我们从这个开始:

static void Main()
{
Random r = new Random();
bool lucky = false;
int maxTries, minValue, maxValue, guess = 0;

GetInput("Enter number of tries: ", out maxTries);
GetInput("Enter minimum number : ", out minValue);
GetInput("Enter maximum number : ", out maxValue);

int magical = r.Next(minValue, maxValue); // only once
for (int i = 1; i <= maxTries; i++)
{
GetInput("Enter your guess : ", out guess);
if (guess == magical)
{
lucky = true;
break;
}
}

Console.WriteLine("you.Lucky = {0};", lucky);
Console.ReadLine();
}

static void GetInput(string text, out int variable)
{
do Console.Write(text); // avoiding stackoverflow.com scroll
while (!Int32.TryParse(Console.ReadLine(), out variable));
}

如果你想从一个文件中获取你的号码,试试像这样的东西:

List<int> magicals = new List<int>();
using (StreamReader reader = new StreamReader("GuessGame.txt"))
{
int magical = 0;
string line = "";
while (!String.IsNullOrEmpty(line = reader.ReadLine()))
{
if (Int32.TryParse(line, out magical))
magicals.Add(magical);
}
}

测试是这样的:

if(magicals.Contains(guess))

关于c# - 猜谜和数字比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com