穷举 迭代
//1、一张150元购物卡,三类洗化用品,洗发水15元,香皂2元,牙刷5元
//求刚好花完150元,有多少种买法,每种买法各买几样?
//洗发水 x 香皂 z 牙刷 y
int count = 0;
int bian = 0;
for (int x = 0; x <= 10; x++)
{
for (int y = 0; y <= 30; y++)
{
for (int z = 0; z <= 75; z++)
{
bian++;
if (15 * x + 5 * y + 2 * z == 150)
{
count++;
Console.WriteLine("第" + count + "种买法洗发水" + x + "瓶,香皂" + z + "块,牙刷" + y + "支");
}
}
}
}
Console.WriteLine("一共循环了" + bian + "遍");
Console.WriteLine("一共有" + count + "种买法");
Console.ReadLine();
//公鸡二文钱一只,母鸡一文钱一只,小鸡半文钱一只,现在有100文钱,要买一百只鸡,
//正好花完100文钱,共有多少种买法,每种各买几只?
int count = 0;
int bian = 0;
for (int gong = 0; gong <= 50; gong++)
{
for (int mu = 0; mu <= 100; mu++)
{
for (int xiao = 0; xiao <= 200; xiao++)
{
bian++;
if (gong + mu + xiao == 100 && gong * 2 + mu * 1 + xiao * 0.5 == 100)
{
count++;
Console.WriteLine("第" + count + "种买法公鸡" + gong + "只,母鸡" + mu + "只,小鸡" + xiao + "只");
}
}
}
}
Console.WriteLine("一共循环了" + bian + "遍");
Console.WriteLine("共有" + count + "种买法");
Console.ReadLine();
//for循环变形得到while循环
//初始条件拿到前面,循环的状态改变放到循环体的最后一句
//for变成while,将原先的分号去掉,只留下循环条件
//数字1~10,累加求和
int sum = 0;
int i = 1;
while (i <= 10)
{
sum += i;
i++;
}
Console.WriteLine(sum);
//公鸡二文钱一只,母鸡一文钱一只,小鸡半文钱一只,现在有100文钱,要买一百只鸡,
//正好花完100文钱,共有多少种买法,每种各买几只? 用while循环
int count = 0;
int bian = 0;
int gong = 0;
while (gong <= 50)
{
int mu = 0;
while (mu <= 100)
{
int xiao = 0;
while (xiao <= 200)
{
bian++;
if (gong + mu + xiao == 100 && gong * 2 + mu * 1 + xiao * 0.5 == 100)
{
count++;
Console.WriteLine("第" + count + "种买法公鸡" + gong + "只,母鸡" + mu + "只,小鸡" + xiao + "只");
}
xiao++;
}
mu++;
}
gong++;
}
Console.WriteLine("共有" + count + "种买法");
Console.WriteLine("共循环了" + bian + "遍");
Console.ReadLine();
//迭代
//纸张厚度0.07毫米
//折叠多少次可以超过珠峰高度8848米
double a = 0;
double i = 0.07;
while (i <= 8848000)
{
a++;
i *= 2;
}
Console.WriteLine(a);
//大马驼2石粮食,中等马驼1石粮食,两头小马驼1石粮食,要用100匹马,驼100石粮食,该如何分配?
int count = 0;
int bian = 0;
for (int dm = 0; dm <= 50; dm++)
{
for (int zm = 0; zm <= 100; zm++)
{
for (int xm = 0; xm <= 200; xm++)
{
bian++;
if (dm + zm + xm == 100 && dm * 2 + zm * 1 + xm * 0.5 == 100)
{
count++;
Console.WriteLine("第" + count + "种方法大马" + dm + "匹,中等马" + zm + "匹,小马" + xm + "匹");
}
}
}
}
Console.WriteLine("一共循环了" + bian + "遍");
Console.WriteLine("一共有" + count + "种方法");
Console.ReadLine();
//有1分钱,2分钱,5分钱的硬币,要组合出来2角钱,有几种组合方式,分别各多少个?
int count = 0;
int bian = 0;
for (int yf = 0; yf <= 20; yf++)
{
for (int ef = 0; ef <= 10; ef++)
{
for (int wf = 0; wf <= 4; wf++)
{
bian++;
if (yf * 1 + ef * 2 + wf * 5 == 20)
{
count++;
Console.WriteLine("第" + count + "种组合方式1分硬币" + yf + "个,2分硬币" + ef + "个,5分硬币" + wf + "个");
}
}
}
}
Console.WriteLine("共有" + count + "种组合方式");
Console.WriteLine("共循环了" + bian + "遍");
Console.ReadLine();
//输入一个100以内的整数,求从1加到这个数的和,如果输入的数不在0到100之间,提示请重新输入
for (; ; )
{
Console.Write("请输入一个100以内整数:");
int a = int.Parse(Console.ReadLine());
int sum = 0;
if (a >= 0 && a <= 100)
{
for (int i = 0; i <= a; i++)
{
sum += i;
}
Console.WriteLine(sum);
break;
}
else
{
Console.WriteLine("您的输入有误,请重新输入");
}
}
Console.ReadLine();