将查找素数的算法的结果存储在文件中(c#)
本文关键字:文件 结果 查找 算法 存储 | 更新日期: 2023-09-27 17:54:48
我正在尝试制作一个程序,查找素数,在控制台中显示它们并将数字存储在文件中。该程序已经将数字存储在一个文件中,但它没有在控制台中显示数字。下面是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Priemgetallen
{
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("C://Users//mens//Documents//PriemGetallen.txt"))
{
Console.SetOut(writer);
Act();
}
}
static void Act()
{
double maxGetal = double.MaxValue;
Console.WriteLine("--- Primes between 0 and 100 ---");
for (int i = 0; i < maxGetal; i++)
{
bool prime = PrimeTool.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}
}
public static class PrimeTool
{
public static bool IsPrime(int candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
// Note:
// ... This version was changed to test the square.
// ... Original version tested against the square root.
// ... Also we exclude 1 at the end.
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
}
}
这是因为Console.SetOut(writer);
这一行。您正在向文件发送控制台输出。
与其这样做,不如放弃StreamWriter
,而是使用:
if (prime)
{
var primeText = string.Format("Prime: {0}", i);
Console.WriteLine(primeText );
File.AppendAllText(@"C:'Users'mens'Documents'PriemGetallen.txt",
primeText + Environment.NewLine);
}