我需要在循环中生成200个数字和符号,这些数字和符号将创建如下内容: 1 + 1或20 * 1252 有没有办法做到这一点? 我是c#的新手。有人可以帮忙吗?
Random randonNum = new Random();
for (int i = 0; i < 200; i++)
{
int nums = randonNum.Next(0, 500);
//dont know how to continue
}
答案 0 :(得分:2)
您似乎知道如何生成随机数,因此生成两个随机数不应该证明任何问题。您似乎无法生成随机的&#34;符号&#34;,称为运营商。
您可以通过创建包含可能选项的数组,为该数组生成随机索引并通过数组索引器检索该元素,如Access random item in list中所述:
var operators = new[] { "+", "-", "/", "*" };
int operatorIndex = randomNum.Next(operators.Length);
var selectedOperator = operators[operatorIndex];
答案 1 :(得分:1)
对所有三个因素使用Random
怎么样?例如,Random
可用于从列表或数组中查找运算符。
您可以使用类似的内容(其中operators
是string
个对象的数组):
string[] operators = new string[] { "+", "-", "*" };
string oper = operators[randonNum.Next(operators.Length)];
看看这个工作示例:
// this list will contain the results
List<string> list = new List<string>();
// create an array of allowed operators
string[] operators = new string[] { "+", "-", "*" };
Random randonNum = new Random();
for (int i = 0; i < 200; i++)
{
// pick two numbers
int num1 = randonNum.Next(0, 500);
int num2 = randonNum.Next(0, 500);
// pick an operator from the array
string oper = operators[randonNum.Next(operators.Length)];
// add it to the list
list.Add(string.Format("{0}{1}{2}", num1, oper, num2));
}
答案 2 :(得分:0)
像这样的东西
string[] operands = new[] {"+", "-", "*", "/"};
Random random = new Random();
List<string> results = new List<string>();
for (int i = 0; i < 200; i++)
{
int firstNum = random.Next(0, 500);
int secondNum = random.Next(0, 500);
string operand = operands[random.Next(0, 3)];
results.Add(string.Format("{0}{1}{2}", firstNum, operand, secondNum));
}