Console.WriteLine输出问题
题目是编程输出1000以内的所有素数。程序代码:
namespace ConsoleApplication18 { class Program { static void Main(string[] args) { Console.WriteLine("2是素数"); //fun1 int count1 = 0; for (int i = 3; i < 1000; ++i) { if (IsPrime(i)) { Console.WriteLine("{0}是素数", i); count1++; } else Console.WriteLine("{0}不是素数", i); } Console.WriteLine("\n\n\n\n\n"); //fun2 int count2 = 1; int[] arr = new int[1000]; for(int i = 0; i < 1000; ++i) arr[i] = i + 1; foreach (int temp in arr) { if (temp > 2) { if (IsPrime(temp)) { Console.WriteLine("{0}是素数", temp); count2++; } } } Console.WriteLine("1000内的素数有{0}个",count2); } public static bool IsPrime(int num) { for (int loop = 2; loop <= Math.Sqrt(num); ++loop) { if (0 == num % loop) return false; } return true; } } }
用fun2 foreach就可以把所有结果输出;只用fun1的话输出只有701到999;fun1和fun2都写的话fun1只有875到999,fun2完整输出;Console.WriteLine("2是素数")这句也没输出。