标签:
for循环
穷举:所有情况走一遍,使用if筛选出符合的情况。
1.单位给发了一张150元购物卡,拿着到超市买三类洗化用品。洗发水15元,香皂2元,牙刷5元。求刚好花完150元,有多少种买法,没种买法都是各买几样?
int d=0; int e = 0; for (int a = 1; a <= 10;a++ ) { for (int b = 1; b <= 30;b++ ) { for (int c = 1; c <= 75;c++ ) { if(a*15+b*5+c*2==150) { d++; Console.WriteLine("第{0}种买法,洗发水{1}瓶,牙刷{2}支,香皂{3}块",d,a,b,c); } } } } Console.WriteLine("总共有"+d+"买法");
2.百鸡百钱:公鸡2文钱一只,母鸡1文钱一只,小鸡半文钱一只,总共只有100文钱,如何在凑够100只鸡的情况下刚好花完100文钱?
double d = 0; double e = 0; for (int a = 0; a <= 50;a++ ) { for (int b = 0; b <= 100;b++ ) { for (int c = 0; c <= 200;c++ ) { d = a + b + c; e = a * 2 + b + c * 0.5; if(d==100&&e==100) { Console.WriteLine("公鸡"+a+"母鸡"+b+"小鸡"+c); } } } }
迭代:
从初始情况按照规律不断求解中间情况,最终推导出结果。
1.理想状态下,篮球自由落体弹起高度若为上一次高度的四分之三首先高度设置为20米,输入一个次数,求篮球现在弹起的高度
Console.Write("输入你想查看的次数"); double a = double.Parse(Console.ReadLine()); double b = 20; for (double i = 1; i <= a;i++ ) { b *= 0.75; } Console.WriteLine(b);
2.要组合出来12元钱,有1分钱,2分钱,5分钱的硬币,有几种组合方式,分别各多少个?
int d = 0; for (int a = 0; a <= 1200; a++) { for (int b = 0; b <= 600; b++) { for (int c = 0; c <= 240; c++) { if (a + 2 * b + 5 * c == 1200) { Console.WriteLine(a + "1分钱" + b + "2分钱" + c + "五分钱"); d++; } } } }
while 循环
其实是for循环的变形写法
for(int i = 1; i<=5;i++)
{
循环体;
}
上面的for循环可以写成
int i= 1;
for(;i<=5;)
{
循环体;
i++;
}
写成while就是以下样式
int i= 1;
while(表达式(i<=5))
{
循环体;
状态改变(i++);
}
do
{
循环体;
状态改变(i++);
}while(表达式(i<=5))
注意:do while是不管满不满足表达式,都会先执行一遍。
1.单位给发了一张150元购物卡,拿着到超市买三类洗化用品。洗发水15元,香皂2元,牙刷5元。求刚好花完150元,有多少种买法,没种买法都是各买几样?
int a = 0; int x = 0; while (x <= 10) { int y = 0; while (y <= 30) { int z = 0; while (z <= 75) { if (x * 15 + y * 5 + z * 2 == 150) { a++; Console.WriteLine("洗发水" + x + "牙刷" + y + "香皂" + z); } z++; } y++; } x++; } Console.WriteLine(a);
2.兔子生兔子问题
Console.Write("输入月数"); int a = int.Parse(Console.ReadLine()); int ct = 0; int xt = 0; int yt = 1; int sum = 1; int i = 1; while (i <= a) { if (i == 1) { ct = 0; xt = 0; yt = 1; sum = 1; } else { ct = ct + xt; xt = yt; yt = ct; sum = ct + xt + yt; } i++; }; Console.WriteLine("成兔" + ct + "小兔" + xt + "幼兔" + yt); Console.WriteLine("对数" + sum);
3.3.求100以内质数的和
int c = 1; int sum = 0; while (c <= 100) { int a = 1; int b = 0; while (a <= c) { if (c % a == 0) { b++; } a++; } if (b == 2) { sum += c; Console.WriteLine(c); } c++; } Console.WriteLine(sum);
百鸡百钱:
int a = 0; int d = 0; while (a <= 50) { int b = 0; while (b <= 100) { int c = 0; while (c <= 200) { if (a + b + c == 100 && 2 * a + b + 0.5 * c == 100) { Console.WriteLine("公鸡" + a + "母鸡" + b + "小鸡" + c); } c++; } b++; } a++; d++; } Console.WriteLine(d + "种");
标签:
原文地址:http://www.cnblogs.com/1030351096zzz/p/5950705.html