【发布时间】:2015-06-07 09:56:36
【问题描述】:
您好,我一直在想办法让它发挥作用时遇到问题。它是 旨在使用用户输入来设置 x 来查找前 x 个素数。然后它将在打印结果之前将任何放入数组中。我想我对循环提出了问题,因为一旦输入用户输入,什么都不会发生。如果有人能指出我哪里出错并提供如何解决它的建议,我将不胜感激。谢谢
static void Main(string[] args)
{
int max, i, count;
i = 0; // this is used to keep trck of how many primes have been added to the array
count = 0; // this is used to test each number
Console.WriteLine("This will work out the first x prime numbers with x being the number of prime numbers you want");
Console.WriteLine("Enter the number of prime numbers you want.");
max = Convert.ToInt32(Console.ReadLine());
int[] primes = new int[max];
while (i <= max)
{
while (count <= 9999)
{
if (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 ) // tests if count number is a prime
{
if (count == 2 || count == 3 ||count == 5 ||count == 7 ) // ensures 2,3,5,7 are added to primes if neccesarry
{
primes[count] = count; //add to array
i++; // increments the count on the number of prime numbers
}
count ++; // increments the count
break;
}
else
{
primes[count] = count;
i++;
count ++;
}
}
}
Console.WriteLine("The first {0} prime numbers are ... ", max);
foreach(var item in primes)
{
Console.Write(item.ToString() + ", ");
}
}
【问题讨论】:
-
计算测试 121 (=11*11) 时会发生什么。它不能被 2,3,5 或 7 整除...
标签: c# loops console-application nested-loops