有没有比我在这里做的更优雅的方式来进行位大小选择和伪随机二进制位生成?实际上我需要编写一个算法,让用户控制生成的随机二进制位的位大小(最大 16 位)。这是我写的函数,但我不确定这是否是最小/最优雅的。由于这是科学需要,效率并不重要,但代码的优雅和易于理解确实很重要。那么有没有更有效/更优雅的方式来做同样的事情?
static string randomBit() {
int bitSize = 0, input = 0;
Console.Write("Input Bit Size (Maximum is 16 Bit): ");
input = Convert.ToInt32(Console.ReadLine());
Random choice = new Random();
if(input == 0 || input > 16) {
bitSize = 0;
}
else if(input == 1) {
bitSize = 1;
}
else if(input == 2) {
int randomChoice = choice.Next(2, 3);
bitSize = randomChoice;
}
else if(input == 3) {
int randomChoice = choice.Next(4, 7);
bitSize = randomChoice;
}
else if(input == 4) {
int randomChoice = choice.Next(8, 15);
bitSize = randomChoice;
}
else if(input == 5) {
int randomChoice = choice.Next(16, 31);
bitSize = randomChoice;
}
else if(input == 6) {
int randomChoice = choice.Next(32, 63);
bitSize = randomChoice;
}
else if(input == 7) {
int randomChoice = choice.Next(64, 127);
bitSize = randomChoice;
}
else if(input == 8) {
int randomChoice = choice.Next(128, 255);
bitSize = randomChoice;
}
else if(input == 9) {
int randomChoice = choice.Next(256, 511);
bitSize = randomChoice;
}
else if(input == 10) {
int randomChoice = choice.Next(512, 1023);
bitSize = randomChoice;
}
else if(input == 11) {
int randomChoice = choice.Next(1024, 2047);
bitSize = randomChoice;
}
else if(input == 12) {
int randomChoice = choice.Next(2047, 4095);
bitSize = randomChoice;
}
else if(input == 13) {
int randomChoice = choice.Next(4096, 8191);
bitSize = randomChoice;
}
else if(input == 14) {
int randomChoice = choice.Next(8192, 16383);
bitSize = randomChoice;
}
else if(input == 15) {
int randomChoice = choice.Next(16384, 32767);
bitSize = randomChoice;
}
else if(input == 16) {
int randomChoice = choice.Next(32768, 65535);
bitSize = randomChoice;
}
string binary = Convert.ToString(bitSize, 2);
return binary;
}
同样作为第二个问题,如果我在代码询问位大小时按 Enter 两次,它会返回异常错误。有没有办法绕过相同的?