将在文件中查找素数的算法的结果存储 (C#)
Store the outcome of an algorithm that looks for prime numbers in a file (C#)
我正在尝试制作一个程序来查找质数,将它们显示在控制台中并将这些数字存储在一个文件中。该程序已经将数字存储在一个文件中,但它不会在控制台中显示数字。这是我的代码:
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);
}
我正在尝试制作一个程序来查找质数,将它们显示在控制台中并将这些数字存储在一个文件中。该程序已经将数字存储在一个文件中,但它不会在控制台中显示数字。这是我的代码:
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);
}