C# - 如何显示小数点后 3 位数字(小数点外 4 位数字)的每个组合

C# - How to show every combination of a 3 decimal placed number (4 numbers outside of the decimals)

我想知道如何写出一个小数点后三位的所有可能组合。

您可能已经猜到我将其用于 IP 地址,因此我需要 4 位小数在 0 到 255 之间。 有什么办法可以在控制台应用程序中编写 4 位小数 (0.0.0.0 - 255.255.255.255) 的每个组合?如果可以做到这一点,那么答复将很棒。感谢阅读!

是的,您可以使用如下简单的嵌套 for 循环来实现:

public class Program
{
    public static void Main(string[] args)
    {
        for (int a = 0; a < 256; a++)
        {
           for (int b = 0; b < 256; b++)
           {
               for (int c = 0; c < 256; c++) 
               {
                   for (int d = 0; d < 256; d++)
                   {
                       string ipAddress = string.Format("{0}.{1}.{2}.{3}", a, b, c, d);
                       Console.WriteLine(ipAddress);
                   }
               }
           }
        }
    }
}

既然你可以 convert an IP4 address to integer,你可以在一个 for 循环中完成:

for (uint i = 0; i <= 4294967295; i++)
{
    byte[] bytes = BitConverter.GetBytes(i);
    Array.Reverse(bytes);
    string ipAddress = new IPAddress(bytes).ToString();
    Console.WriteLine(ipAddress);
}