随机4个数看是否能通过加减乘除算出24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Operation text = new Operation();
text.Opr();
Console.Read();
}
}
public class Operation
{
int num = 4; //数组里元素的个数
int Number = 0;
string str1 = null;
string str2 = null;
public void Opr()
{
//初始化数组
Random r1 = new Random();
int[] r2 = { 4, 4, 4, 4 };
for (int j = 0; j < 4; j++)
{
int a = 0;
a = r1.Next(0, 10);
r2[j] = a;
}
Console.Write("随机的四个数为{0},{1},{2},{3}", r2[0], r2[1], r2[2], r2[3]);
Console.WriteLine();
getNumber(num, r2);
}
public void getNumber(int num,int []r)
{
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num && j != i; j++)
{
if(num == 4)
{
for (int k = 0; k < 4; k++)
{
switch (k)
{
case 0: Number = r[i] + r[j]; str1 = r[i].ToString() + "+" + r[j].ToString() + "=" + Number; show(i, j, Number, r, num); break;
case 1: Number = r[i] - r[j]; str1 = r[i].ToString() + "-" + r[j].ToString() + "=" + Number; show(i, j, Number, r, num); break;
case 2: Number = r[i] * r[j]; str1 = r[i].ToString() + "*" + r[j].ToString() + "=" + Number; show(i, j, Number, r, num); break;
case 3: if (r[j] != 0) { Number = r[i] / r[j]; str1 = r[i].ToString() + "/" + r[j].ToString(); show(i, j, Number, r,num); } break;
}
}
}
if (num == 3)
{
for (int k = 0; k < 4; k++)
{
switch (k)
{
case 0: Number = r[i] + r[j]; str2 = r[i].ToString() + "+" + r[j].ToString() + "=" + Number; show(i, j, Number, r,num); break;
case 1: Number = r[i] - r[j]; str2 = r[i].ToString() + "-" + r[j].ToString() + "=" + Number; show(i, j, Number, r,num); break;
case 2: Number = r[i] * r[j]; str2 = r[i].ToString() + "*" + r[j].ToString() + "=" + Number; show(i, j, Number, r,num); break;
case 3: if (r[j] != 0) { Number = r[i] / r[j]; str2 = r[i].ToString() + "/" + r[j].ToString() + "=" + Number; show(i, j, Number, r,num); } break;
}
}
}
if (num == 2)
{
for (int k = 0; k < 4; k++)
{
switch (k)
{
case 0: Number = r[i] + r[j]; if (Number == 24) { Console.Write("第一步" + str1 + "第二步 " + str2 + "第三步" + r[i] + "+" + r[j] + "=" + Number); } break;
case 1: Number = r[i] - r[j]; if (Number == 24) { Console.Write("第一步" + str1 + "第二步 " + str2 + "第三步" + r[i] + "-" + r[j] + "=" + Number); } break;
case 2: Number = r[i] * r[j]; if (Number == 24) { Console.Write("第一步" + str1 + "第二步 " + str2 + "第三步" + r[i] + "*" + r[j] + "=" + Number); } break;
case 3: if (r[j] != 0) { Number = r[i] / r[j]; } if (Number == 24) { Console.Write("第一步" + str1 + "第二步 " + str2 + "第三步" + r[i] + "/" + r[j] + "=" + Number); } break;
}
}
}
}
}
}
public void show(int i,int j,int Number,int []r,int num)
{
int[] a = new int[3];
int b = 0;
for(int m=0;m<num;m++)
{
if (m != i && m != j)
{
a[b++] = r[m];
}
}
a[b] = Number;
num = num - 1;
getNumber(num, a);
}
}
}