[英]My C# code using System.IO.StreamWriter outputs random chinese/unicode characters at a certain length
我一直在嘗試將代碼寫入 output 文檔中從 3 到int limit
的所有素數(使用 System.IO.StreamWriter)以及控制台。 這是我寫的代碼:
using System;
using System.IO;
namespace primes
{
class Program
{
static void Main(string[] args)
{
string output = "";
a:
Console.Write("Numbers to test >> ");
string limitStr = Console.ReadLine();
int limit = Convert.ToInt32(limitStr);
if (limit < 3)
{
Console.WriteLine("Write an integer above 2.\n");
goto a;
}
DateTime start = DateTime.Now;
for (int i = 0; i < limit; i++)
{
for (int j = 2; j < i; j++)
{
if (j == Math.Ceiling(Convert.ToDouble(i / 2)) + 1)
{
Console.WriteLine(i + " is prime.");
output += Convert.ToString(Convert.ToString(i) + "\n");
}
else if (i % j == 0)
{
goto b;
}
}
b:;
}
using (System.IO.StreamWriter sw = new StreamWriter("primes.txt"))
{
sw.Write(output);
}
string timeElapsed = Convert.ToString((DateTime.Now - start).TotalSeconds);
Console.Write("\nTook " + timeElapsed + " seconds to run.");
ConsoleKeyInfo k;
Console.WriteLine("\nPress ESC to exit...");
while (true)
{
k = Console.ReadKey(true);
if (k.Key == ConsoleKey.Escape)
break;
}
}
}
}
當使用int limit = 50
我在文本文檔中得到這個 output :
3
5
7
11
13
17
19
23
29
31
37
41
43
47
但是當int limit = 1260
時,它會輸出:
ਲ਼ਵㄱㄊਲ਼㜱ㄊਹ㌲㈊ਹㄳ㌊ㄴ㐊ਲ਼㜴㔊ਲ਼㤵㘊㜶㜊㌷㜊ਹ㌸㠊ਹ㜹ㄊㄊ㌰ㄊ㜰ㄊ㤰ㄊ㌱ㄊ㜲ㄊㄳㄊ㜳ㄊ㤳ㄊ㤴ㄊㄵㄊ㜵ㄊ㌶ㄊ㜶ㄊ㌷ㄊ㤷ㄊㄸㄊㄹㄊ㌹ㄊ㜹ㄊ㤹㈊ㄱ㈊㌲㈊㜲㈊㤲㈊㌳㈊㤳㈊ㄴ㈊ㄵ㈊㜵㈊㌶㈊㤶㈊ㄷ㈊㜷㈊ㄸ㈊㌸㈊㌹㌊㜰㌊ㄱ㌊㌱㌊㜱㌊ㄳ㌊㜳㌊㜴㌊㤴㌊㌵㌊㤵㌊㜶㌊㌷㌊㤷㌊㌸㌊㤸㌊㜹㐊㐊㤰㐊㤱㐊ㄲ㐊ㄳ㐊㌳㐊㤳㐊㌴㐊㤴㐊㜵㐊ㄶ㐊㌶㐊㜶㐊㤷㐊㜸㐊ㄹ㐊㤹㔊㌰㔊㤰㔊ㄲ㔊㌲㔊ㄴ㔊㜴㔊㜵㔊㌶㔊㤶㔊ㄷ㔊㜷㔊㜸㔊㌹㔊㤹㘊㘊㜰㘊㌱㘊㜱㘊㤱㘊ㄳ㘊ㄴ㘊㌴㘊㜴㘊㌵㘊㤵㘊ㄶ㘊㌷㘊㜷㘊㌸㘊ㄹ㜊㜊㤰㜊㤱㜊㜲㜊㌳㜊㤳㜊㌴㜊ㄵ㜊㜵㜊ㄶ㜊㤶㜊㌷㜊㜸㜊㜹㠊㤰㠊ㄱ㠊ㄲ㠊㌲㠊㜲㠊㤲㠊㤳㠊㌵㠊㜵㠊㤵㠊㌶㠊㜷㠊ㄸ㠊㌸㠊㜸㤊㜰㤊ㄱ㤊㤱㤊㤲㤊㜳㤊ㄴ㤊㜴㤊㌵㤊㜶㤊ㄷ㤊㜷㤊㌸㤊ㄹ㤊㜹ㄊ〰ਹ〱㌱ㄊਹ〱ㄲㄊ㌰〱㌳ㄊ㌰ਹ〱㤴ㄊ㔰〱ㄶㄊ㘰ਲ਼〱㤶ㄊ㠰〱ㄹㄊ㤰ਲ਼〱㜹ㄊ〱ਲ਼ㄱ㤰ㄊㄱㄱ㌲ㄊ㈱ਹㄱㄵㄊ㔱ਲ਼ㄱ㌶ㄊ㜱ㄱㄸㄊ㠱ㄱ㌹ㄊ〲㈱㌱ㄊㄲ㈱㌲ㄊ㈲ਹ㈱ㄳㄊ㌲㈱㤴ㄊ㔲ਹ
這個行話繼續用越來越大的數字,更多的字符,有時在文本中會出現一些模式。 我究竟做錯了什么? 它在控制台中看起來很好。
信息:使用 Visual Studio Community 2019 進行編輯
使用Windows 10 Home Notepad.exe訪問primes.txt
您需要在 StreamWriter output 上為您的文本文件指定文本編碼類型。
代替:
using (System.IO.StreamWriter sw = new StreamWriter("primes.txt"))
和
using (System.IO.StreamWriter sw = new StreamWriter("primes.txt", false, System.Text.Encoding.UTF8))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.