我刚开始学习c#。我对是否以及是否感到最自在。现在,我正在编写一个程序,在该程序中写入IP地址,然后需要键入正确的子网以及所有其他内容。使用if和else if编写代码花费的时间太长,所以我想知道是否有更快的方法。
Random r = new Random();
int randomip = r.Next(256);
int secondip = r.Next(256);
int subnetip = r.Next(24, 31);
int numbers = subnetip;
Console.WriteLine("192.168." + randomip + "." + secondip + "/" + subnetip);
Console.Write("Type the correct netID: ");
Console.ReadLine();
Console.Write("Type the correct subnet: ");
Console.ReadLine();
if (numbers == 24)
{
Console.WriteLine("correct netID is: 192.168." + randomip +
"." + secondip / 256);
Console.WriteLine("correct subnet is: 255.255.255.0");
} else if (numbers == 25)
{
Console.WriteLine("correct netID is: 192.168." + randomip +
"." + secondip / 128);
Console.WriteLine("correct subnet is: 255.255.255.128");
} else if (numbers == 26)
,依此类推……还有其他数字。有没有更快,更轻松的方法来使其工作?可以,但是如果我想添加更多数字,将会出现问题
答案 0 :(得分:11)
如果您倒想,这些就是基于numbers
的除数
31 => 2
30 => 4
29 => 8
28 => 16
27 => 32
26 => 64
25 => 128
24 => 256
换句话说,它们是递增数字的幂的两倍。
31 => 2^1
30 => 2^2
29 => 2^3
28 => 2^4
27 => 2^5
26 => 2^6
25 => 2^7
24 => 2^8
换句话说,2乘以32的幂减去numbers
31 => 2^(32-31)
30 => 2^(32-30)
29 => 2^(32-29)
28 => 2^(32-28)
27 => 2^(32-27)
26 => 2^(32-26)
25 => 2^(32-25)
24 => 2^(32-24)
换句话说,
var divisor = Math.Pow(2, 32-numbers);
var subnet = 256 - divisor;
最多4行,没有switch
或if
。是的!
Console.WriteLine("correct netID is: 192.168." + randomip + "." + secondip / divisor);
Console.WriteLine("correct subnet is: 255.255.255." + subnet);