繁体   English   中英

我的 C# 代码使用 System.IO.StreamWriter 输出一定长度的随机中文/unicode字符

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM