for循环嵌套
七、for循环嵌套
(一)格式
for(初始条件;循环条件;循环调整)
{
for(初始条件;循环条件;循环调整)
{
循环体
}
}
(二)例题
1、一个游戏,前20关每一关是自身的分数,21~30关每一关是10分,31~40关每一关是20分,41~49关每一关是30分,第50关是100分,输入你现在闯到的关卡数,求你现在拥有的分数。
主要代码:
(1)法一
while (true)
{
Console.Write("请输入你闯到的关卡:");
int c = int.Parse(Console.ReadLine());
if (c >= 1 && c <= 50)
{
int p = 0;
if (c <= 20)
{
for (int i = 0; i <= c; i++)
p += i;
}
else if (c <= 30)
{
for (int i = 0; i <= 20; i++)
p += i;
for (int i = 21; i <= c; i++)
p += 10;
}
else if (c <= 40)
{
for (int i = 0; i <= 20; i++)
p += i;
for (int i = 21; i <= 30; i++)
p += 10;
for (int i = 31; i <= c; i++)
p += 20;
}
else if (c >= 41 && c < 49)
{
for (int i = 0; i <= 20; i++)
p += i;
for (int i = 21; i <= 30; i++)
p += 10;
for (int i = 31; i <= 40; i++)
p += 20;
for (int i = 41; i <= c; i++)
p += 30;
}
else
{
for (int i = 0; i <= 20; i++)
p += i;
for (int i = 21; i <= 30; i++)
p += 10;
for (int i = 31; i <= 40; i++)
p += 20;
for (int i = 41; i <= 49; i++)
p += 30;
for (int i = 50; i <= c; i++)
p += 100;
}
Console.WriteLine("您已获得{0}分!", p);
}
else
Console.WriteLine("您输入关卡有误!");
}
Console.ReadLine();
(2)法二
while (true)
{
Console.Write("请输入你闯到的关卡:");
int c = int.Parse(Console.ReadLine());
if (c >= 1 && c <= 50)
{
int p = 0;
for (int i = 1; i <= c; i++)
{
if (i >= 1 && i <= 20)
p += i;
else if (i >= 21 && i <= 30)
p += 10;
else if (i >= 31 && i <= 40)
p += 20;
else if (i >= 41 && i <= 49)
p += 30;
else
p += 100;
}
Console.WriteLine("您已获得{0}分!", p);
}
else
Console.WriteLine("您输入关卡有误!");
}
Console.ReadLine();
结果:
2、菱形
主要代码:
for (int i = 1; i <= 5; i++)
{
for (int j = 4; j >= i; j--)
Console.Write(" ");
for (int k = 1; k <= i; k++)
Console.Write("☆");
for (int m = 1; m <= i - 1; m++)
Console.Write("☆");
Console.WriteLine();
}
for (int n = 1; n <= 4; n++)
{
for (int a = 1; a <= n; a++)
Console.Write(" ");
for (int b = 3; b >= n; b--)
Console.Write("☆");
for (int b = 3; b >= n - 1; b--)
Console.Write("☆");
Console.WriteLine();
}
Console.ReadLine();
结果:
3、有一对幼兔,幼兔一个月后长成小兔,小兔一个月后长成成兔并生下一对幼兔,问几年后有多少对兔子,幼兔,小兔,成兔分别是多少。(成兔每月生下一对幼兔)
主要代码:
//先计算一年内的兔子对数,在算两年以后的对数
while (true)
{
Console.Write("请输入年份:");
int year = int.Parse(Console.ReadLine());
if (year >= 1)
{
Console.Write("请输入月份:");
int mouth = int.Parse(Console.ReadLine());
if (mouth >= 1 && mouth <= 12)
{
int y = 1;
int x = 0;
int c = 0;
int s = 1;
//第一年兔子对数
if (year == 1)
{
for (int i = 1; i <= mouth; i++)
{
//第一个月特殊,先算
if (i == 1)
{
y = 1;
x = 0;
c = 0;
}
else
{
c += x;
x = y;
y = c;
}
s = c + x + y;
}
}
//第二年兔子对数
else
{
int m = 12;
for (int k = 2; k <= year; k++)
{
//先把上一年的总数算出,再算下一年的
for (int i = 1; i <= m; i++)
{
if (i == 1)
{
y = 1;
x = 0;
c = 0;
}
else
{
c += x;
x = y;
y = c;
}
s = c + x + y;
}
//本年的兔子对数
for (int j = 1; j <= mouth; j++)
{
c += x;
x = y;
y = c;
s = c + x + y;
}
//执行完后,上一年的总数会增加,因此月份会增加一倍
m+=12;
}
}
Console.WriteLine("第{0}年的第{1}个月有{2}对幼兔,{3}对小兔和{4}对成兔,总共{5}对兔子。", year, mouth, y, x, c, s);
}
else
Console.WriteLine("您输入的不是正确的月份!");
}
else
Console.WriteLine("你输入的年份无意义!");
}
Console.ReadLine();
结果: