[英]Why doen't the smallest number from user input gets added to the list?
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number.在学校有一个测试,我们必须编写一个 C# 控制台程序,从用户输入中读取 100 以下的正整数,然后写出一些细节,比如最大数。 I used a list to store the numbers.
我用一个列表来存储数字。 I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
我用我输入的一些随机数对其进行了测试,但程序只将数字添加到列表中,从第二小的数字开始。
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?我做错了什么?
For input in console, I think the do...while loop is the ideal construct.对于控制台中的输入,我认为 do...while 循环是理想的构造。 Menus or requesting a number - it covers all of those.
菜单或要求一个号码 - 它涵盖了所有这些。
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it).至于出了什么问题:实际上它将所有数字添加到集合中(调试代码应该确认它)。 You just remove the smalest number from the collection between Sorting and Display:
您只需从排序和显示之间的集合中删除最小的数字:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors."有一种说法:“编程中最常见的两个问题是命名变量、查奇失效和一对一错误。” But this specific to make is somewhat unique :)
但是这个特定的制作有点独特:)
Edit: As Biesi Grr pointed out, you also ignore the first input:编辑:正如 Biesi Grr 指出的那样,您也忽略了第一个输入:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here?也许你想在这里使用 ReadKey() ? There is also no need for a counter - that is actually the job of List.Lenght.
也不需要计数器 - 这实际上是 List.Lenght 的工作。 In any case, a do..while would make that line unessesary any way.
在任何情况下, do..while 都会使该行变得无关紧要。
let us make a fixed, do...while version让我们做一个固定的,做...while 版本
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.