C# 用两个随机数求和,但它必须等于用户输入
本文关键字:于用户 输入 用户 两个 随机数 求和 | 更新日期: 2023-09-27 18:18:33
我想知道是否可以从用户输入 int 中得出总和,但每次总和都必须是 radom。
这是我制作的代码:
public static string genSum(int askedNumber)
{
string outputStr = null;
bool switchOneTwo = false;
int neededSum = 0;
int intOne = 0;
int intTwo = 0;
while (askedNumber != neededSum)
{
if (switchOneTwo == true)
{
intOne += 1;
switchOneTwo = false;
}
else
{
intTwo += 1;
switchOneTwo = true;
}
neededSum = intOne + intTwo;
if (neededSum == askedNumber)
{
if (neededSum >= 4)
{
Random randomInt = new Random();
int tmpIntOne = intOne;
int tmpIntTwo = intTwo;
int method;
//For now only one method
method = randomInt.Next(1, 1);
if (method == 1)
{
tmpIntOne = tmpIntOne / 2;
tmpIntTwo = (tmpIntTwo * 2) - tmpIntOne;
}
intOne = tmpIntOne;
intTwo = tmpIntTwo;
}
outputStr = "(" + intOne.ToString() + "+" + intTwo.ToString() + ")";
return outputStr;
}
}
return outputStr;
}
所以我想要的是,如果用户输入一个数字,例如 20,它将产生一个总和:
用户输入 20 并按 GO!
:结果:
10 + 10 = 20
12 + 8 = 20
5 + 15 = 20
1 + 19 = 20
3 + 17 = 20
用户输入 500 并按 GO!
:结果:
9 + 491 = 500
263 + 237 = 500
300 + 200 = 500
250 + 250 = 500
109 + 391 = 500
创建一个小于输入的随机数,另一个将是User-YourRandom
void Foo(int userNumber)
{
Random r = new Random();
int firstNumber = r.Next(userNumber - 1);
int secondNumber = userNumber - firstNumber;
}
您也可以将其扩展为支持负数。
编辑获取真实随机数
正如 I4V 指出的那样,如果将其放在循环中,您可能会得到相同的一组数字,因此您可以使用此方法而不是调用Random
:
void Foo(int userNumber)
{
int userNumber = 500;
for (int i = 0; i < 10; i++ )
{
int firstNumber = Next(0, userNumber - 1);
int secondNumber = userNumber - firstNumber;
Console.WriteLine(firstNumber + "+" + secondNumber);
}
}
internal static int RandomExt(int min, int max)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[4];
rng.GetBytes(buffer);
int result = BitConverter.ToInt32(buffer, 0);
return new Random(result).Next(min, max);
}
foreach (var s in genSum(500).Take(5))
{
Console.WriteLine(s);
}
public static IEnumerable<string> genSum(int askedNumber)
{
Random r = new Random();
while (true)
{
var i = r.Next(0, askedNumber);
yield return i + "+" + (askedNumber - i);
}
}