如何输入数字列表但确保程序不允许我重复任何数字? [英] How do I input a list of numbers but make sure the program doesn't allow me to repeat any numbers?
问题描述
我做了一个程序,要求我输入10个不同的数字,范围从10到100,数字不能重复。我可以这么做,所以程序不允许10以下或大于100的数字,但我不能这样做,所以他们不会重复而不用很长的代码。
我尝试了什么:
我执行for .... else语句以保持数字10-100的范围。我用它来确保数字也不重复。我越接近输入第十个数字就变得非常冗长。该程序有效,但输入太多。
I made a program asking me to input 10 different numbers ranging from 10 to 100 and the numbers can't repeat. I can make it so the program doesn't allow numbers below 10 or greater than 100, but I can't make it so they don't repeat without making a very long code.
What I have tried:
I do the "for....else" statement to keep the numbers in the 10 - 100 range. I used it to make sure the numbers don't repeat also. It gets very lengthy the closer I get to inputting the tenth number. The program works, but it is too much to type in.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
string userNumber;
string previousNumber = ("");
int numberint;
Console.WriteLine("I need you to enter 10 different numbers ranging from 10 to 100");
for (int number = 0; number < 10; number++)
{
Console.Write("Please enter your number: ");
userNumber = Console.ReadLine();
numberint = int.Parse(userNumber);
if (numberint > 100 || numberint < 10 || userNumber == previousNumber)
{
Console.WriteLine("Invalid number. Please enter a number ranging from 10 to 100");
number--;
}
else
Console.WriteLine("Thank you for entering " + userNumber);
}
推荐答案
您可以使用 HashSet [ ^ ]用于此目的,例如
You might use a HashSet[^] for the purpose, e.g.
HashSet<int> number = new HashSet<int>();
while (number.Count < 10)
{
int candidate;
Console.WriteLine("Please, enter a number between 10 and 100");
if (int.TryParse(Console.ReadLine(), out candidate))
{
if (candidate >= 10 && candidate <= 100)
number.Add(candidate); // adding a duplicate to the HashSet has no effect
}
}
// 'number' contains 10 different integers in the 10..100 range. Showing them:
foreach (int n in number)
Console.WriteLine(n);
这只是伪代码中的一个示例算法来解决您的问题:
This is just an example algorithm in pseudo code to solve your problem:
0. Initialize an array container
1. Get a user input
2. Converted that input to a number
3. IF (that number is between 10 and 100 AND is not already in the array container) THEN
3.1 Add it to that array container
4. Go to 1 if that array container contains less than 10 elements.
您可以使用任何编程语言来实现此算法。有关特定语言的语法和功能,请咨询Google。
You can use any programming language to implement this algorithm. For specific language syntaxes and features, ask Google.
这篇关于如何输入数字列表但确保程序不允许我重复任何数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!