我目前正在网上注册一个C#编程课程。很难联系我的老师寻求帮助,我正在努力解决当前的这个项目,我非常接近,但我的解决方案必须100%与老师的解决方案相匹配。 我必须在列表当前工作导致之前移动错误消息,但没有成功。请帮助我知道这可能是一个愚蠢的错误,但我仍然是一个初学者。 我的代码到目前为止:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace midterm
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("How many numbers will you enter?");
size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
int count = 0;
while (count < size)
{
Console.Write("Enter number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number >= 10 && number <= 100)
{
bool containsNumber = false;
for (int j = 0; j < count; j++)
{
if (number == numbers[j])
containsNumber = true;
if (numbers[j] > 0)
Console.WriteLine("{0}", numbers[j]);
}
if (!containsNumber)
{
if (count < numbers.Length)
numbers[count] = number;
Console.WriteLine(number);
}
else
{
Console.WriteLine("{0} has already been entered", number);
}
++count;
}
else
Console.WriteLine("number must be between 10 and 100");
}
Console.ReadLine();
}
}
}
测试用例:
10
90
50
90
22
18
65
22
92
100
20
正确的解决方案:
How many numbers will you enter?
Enter number: 90
Enter number: 90
50
Enter number: 90 has already been entered
90
50
Enter number: 90
50
22
Enter number: 90
50
22
18
Enter number: 90
50
22
18
65
Enter number: 22 has already been entered
90
50
22
18
65
Enter number: 90
50
22
18
65
92
Enter number: 90
50
22
18
65
92
100
Enter number: 90
50
22
18
65
92
100
20
我的解决方案:
How many numbers will you enter?
Enter number: 90
Enter number: 90
50
Enter number: 90
50
90 has already been entered
Enter number: 90
50
22
Enter number: 90
50
22
18
Enter number: 90
50
22
18
65
Enter number: 90
50
22
18
65
22 has already been entered
Enter number: 90
50
22
18
65
92
Enter number: 90
50
22
18
65
92
100
Enter number: 90
50
22
18
65
92
100
20
答案 0 :(得分:0)
看起来您将不得不移动/复制for循环:
if (number >= 10 && number <= 100)
{
bool containsNumber = false;
for (int j = 0; j < count; j++)
{
if (number == numbers[j])
containsNumber = true;
}
if (!containsNumber)
{
if (count < numbers.Length)
numbers[count] = number;
Console.WriteLine(number);
}
else
{
Console.WriteLine("{0} has already been entered", number);
}
for (int j = 0; j < count; j++)
{
if (numbers[j] > 0)
Console.WriteLine("{0}", numbers[j]);
}
++count;
基本上,您需要在打印列表之前进行检查,但了解输入数字的唯一方法是遍历列表。因此,您必须在检查重复后再次遍历列表以执行打印。
即使使用IEnumerable.Contains(这是Linq建议)也会这样做,但它会更有效地执行它并隐藏丑陋的额外for循环。
如果您有任何疑问,请与我联系!