for循环及for循环的嵌套练习
一、用五角星组成三角形、菱形(三角形共有8种组成方式)
1、第一种:
for (int i = 1; i <= 6; i = i + 1)//i=i+1就表示i++
{
for (int a = 1; a <= i; a = a + 1)
{
Console.Write("☆");
}
for (int b = 5; b >= i; b = b - 1)
{
Console.Write(" ");
}
Console.WriteLine();
}
Console.ReadLine();
2、第二种:
for (int i = 1; i <= 6; i = i + 1)//i=i+1就表示i++
{
for (int a = 5; a >= i; a = a - 1)
{
Console.Write(" ");
}
for (int b = 1; b <= i; b = b + 1)
{
Console.Write("☆");
}
Console.WriteLine();
}
Console.ReadLine();
3、第三种:
for (int i = 1; i <= 6; i = i + 1)
{
for (int a = 6; a >= i; a = a - 1)
{
Console.Write("☆");
}
for (int b = 0; b <= i; b = b + 1)
{
Console.Write(" ");
}
Console.WriteLine();
}
Console.ReadLine();
4、第四种:
for (int i = 1; i <= 6; i = i + 1)
{
for (int a = 0; a <= i; a = a + 1)
{
Console.Write(" ");
}
for (int b = 5; b >= i; b = b - 1)
{
Console.Write("☆");
}
Console.WriteLine();
}
Console.ReadLine();
5、菱形:
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i = i + 1)
{
for (int a = 1; a <= n - i; a = a + 1)
{
Console.Write(" ");
}
for (int b = 1; b <= 2 * i - 1; b = b + 1)
{
Console.Write("☆");
}
Console.WriteLine();
}
for (int h = 1; h < n; h++)
{
for (int c = 1; c <= h; c = c + 1)
{
Console.Write(" ");
}
for (int d = 1; d <= 2 * (n - h) - 1; d = d + 1)
{
Console.Write("☆");
}
Console.WriteLine();
}
Console.ReadLine();
6、有一对幼兔,幼兔1个月后长成小兔,小兔1个月后长成成兔并生下一对幼兔,问几年后有多少对兔子,幼兔、小兔、成兔对数分别是多少。成兔每月生下一对幼兔。
月份 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
成兔对数 |
0 |
0 |
1 |
1 |
2 |
3 |
5 |
小兔对数 |
0 |
1 |
0 |
1 |
1 |
2 |
3 |
幼兔对数 |
1 |
0 |
1 |
1 |
2 |
3 |
5 |
总对数 |
1 |
1 |
2 |
3 |
5 |
8 |
13 |
根据上表可以得到结论:
本月的成兔(ct)=上月的小兔+上月的成兔。
本月的小兔(xt)=上月的小兔。
本月的幼兔(yt)=本月的成兔
总对数(sum)= ct + xt + yt
Console.Write("请输入月份:");
int a = int.Parse(Console.ReadLine());
int ct = 0;//成兔对数
int xt = 0;//小兔对数
int yt = 1;//幼兔对数
int sum = ct+xt+yt;//总对数
//先假设第一个月的成兔、小兔、幼兔的对数
if (a == 1)
{
for (int i = 1; i <= a; i++)
{
ct = 0;
xt = 0;
yt = 1;
sum = ct + xt + yt;//总兔对数等于成兔加小兔加幼兔
}
Console.WriteLine(a.ToString() + "个月后成兔对数是:" + ct.ToString());
Console.WriteLine(a.ToString() + "个月后小兔对数是:" + xt.ToString());
Console.WriteLine(a.ToString() + "个月后幼兔对数是:" + yt.ToString());
Console.WriteLine(a.ToString() + "个月后兔子的总对数是:" + sum.ToString());
}
else
{
for (int i = 2; i <= a; i++)
{
ct = ct + xt;//每月成兔对数等于上月小兔对数+上月成兔对数
xt = yt;//每月小兔对数等于上月幼兔对数
yt = ct;//每月幼兔对数等于本月的成兔对数
sum = ct + xt + yt;//总兔对数等于成兔加小兔加幼兔
}
Console.WriteLine(a.ToString() + "个月后成兔对数是:" + ct.ToString());
Console.WriteLine(a.ToString() + "个月后小兔对数是:" + xt.ToString());
Console.WriteLine(a.ToString() + "个月后幼兔对数是:" + yt.ToString());
Console.WriteLine(a.ToString() + "个月后兔子的总对数是:" + sum.ToString());
}
Console.ReadLine();