15-07-03 语句- for () 循环语句-穷举法
for() 穷举法
用循环把各种可能的情况都走一遍,然后用if条件把满足要求的结果给筛选出来。
例如:
1、找100以内的偶数
for (int i = 0; i <= 100; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i);
}
}
2、小明单位发了50元的购物卡,他到超市买洗化用品,一是牙刷(5元),二是香皂(2元),三是牙膏(10元)怎么可以正好把五十元花完。
for (int ys = 0; ys <= 10; ys++)
{
for (int yg = 0; yg <= 5; yg++)
{
for (int fz = 0; fz <= 25;fz++ )
{
double a = ys * 5 + yg * 10 + fz * 2;
if(a == 50)
{
Console.WriteLine("可以买牙刷"+ys+"只,牙膏"+yg+"只,肥皂"+fz+"只");
}
}
}
}
3、大马驮2石粮食,中马驮1石粮食,两头小马驮一旦粮食,要用100匹马,驮100石粮食,该如何调配
for (int d = 0; d <= 50; d++)
{
for (int x = 0; x <= 100; x++)
{
for (int y = 0; y <= 200; y++)
{
double a = d * 2 + x + y * 0.5;
if (a == 100)
{
Console.WriteLine("用" + d + "匹大马,用" + x + "匹小马,用" + y + "匹幼马");
Thread.Sleep(50);
}
}
}
}
4、有1块,2块,5块的钱若干,凑出20块钱,有几种凑法
for (int a = 0; a <= 20;a++ )
{
for (int b = 0; b <= 10;b++ )
{
for (int c = 0; c <= 4;c++ )
{
int d = a + b * 2 + c * 5;
if (d == 20)
{
Console.WriteLine("需要1块钱"+a+"张,2块钱"+b+"张,5块钱"+c+"张");
}
}
}
}
5、某侦察队接到一项紧急任务,要求在A、B、C、D、E、F六个队员中尽可能多地挑若干人,但有以下限制条件:
侦察兵A和B两人中至少去一人; a+b>=1
A和D不能一起去; a+d<=1
A、E和F三人中要派两人去; a+e+f == 2
B和C都去或都不去; b+c !=1
C和D两人中去一个; c+d==1
若D不去,则E也不去。 d+e==0 || d=1
问应当让哪几个人去?
for (int a = 0; a <= 1; a++)
{
for (int b = 0; b <= 1; b++)
{
for (int c = 0; c <= 1; c++)
{
for (int d = 0; d <= 1; d++)
{
for (int e = 0; e <= 1; e++)
{
for (int f = 0; f <= 1; f++)
{
if (a+b >= 1 && a+d <= 1 && a+e+f == 2 && b+c != 1 && c+d == 1 && (d+e == 0 || d == 1))
{
Console.WriteLine("A:" +a+ "\nB:" +b+ "\nC:" +c+ "\nD:" +d+ "\nE:" +e+ "\nF:" +f);
}
}
}
}
}
}
}
6. 1 () 2 () 3 ()4 = 4;问括号里我要填 (- 或 +)
for (int a=-1;a<=1;a=a+2)
{
for(int b=-1;b<=1;b=b+2)
{
for(int c=-1;c<=1;c=c+2)
{
int d = 1 + a * 2 + b * 3 + c * 4;
if( d == 4)
{
Console.WriteLine("1+"+a*2+"+"+b*3+"+"+c*4+"=4");
}
}
}
}