List<int> numberList = new List<int>();
List<int> uniqueList = new List<int>();
string input;
int number = 0;
bool over = false;
while (!over)
{
input = Console.ReadLine();
if (input == "quit")
{
over = true;
break;
}
if (int.TryParse(input, out number))
{
numberList.Add(number);
}
}
for (int i = 0; i < numberList.Count; i++)
{
if (!uniqueList.Contains(number))
{
uniqueList.Add(number);
}
}
for (int i = 0; i < uniqueList.Count; i++)
{
Console.WriteLine(uniqueList[i]);
}
Console.ReadKey();
你好!我需要这个接受数字的程序的帮助,但是在键入“退出”时,它应该列出所有已输入的唯一数字。
例如这里的输入:5, 5, 5, 2, 2, 1, 3控制台应该只显示1和3,因为它们是唯一的唯一数字。
问题是,当前形式的程序只显示已输入的最后一个唯一数字,而不是全部,我不知道为什么。
你能告诉我为什么吗?我需要做什么才能列出所有这些?
您需要使用字典来记录每个数字的计数,然后返回唯一的:
Dictionary<int, int> numberDictionary = new Dictionary<int, int>();
string input;
int number = 0;
bool over = false;
while (!over)
{
input = Console.ReadLine();
if (input == "quit")
{
over = true;
break;
}
if (int.TryParse(input, out number))
{
if (numberDictionary.TryGetValue(number), out int count)
{
numberDictionary[number] = count + 1;
}
else
{
numberDictionary.Add(number, 1);
}
}
}
foreach(var item in numberDictionary)
{
if (item.Value == 1)
Console.WriteLine(item.Key);
}
Console.ReadKey();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句