while循环
例:
累加1-10.
for循环写成while的形式如下
int a = 0, i = 1;
for (; i <= 10; )//for 变成 while 型
{
a += i;
i++;
}
Console.WriteLine(a);
int a = 0, i = 1;
while (i <= 10)//while 循环 跟for循环的区别就是for( ; i<=a; )变成了while(i<=a)
{
a += i;
i++;
}
Console.WriteLine(a);
百马百担问题
3.大马驼2石粮食,中等马驼1石粮食,两头小马驼1石粮食,要用100匹马,驼100石粮食,该如何分配?
for循环的写法:
int sum = 0;
for (int d = 0; d <= 50; d++)
{
for (int z = 0; z <= 100; z++)
{
for (int x = 0; x <= 200; x += 2)
{
if (d + z + x == 100 && d * 2 + z + x / 2 == 100)
{
Console.WriteLine("需要大马" + d + "头,中马" + z + "头,小马" + x + "头");
sum++;
}
}
}
}
Console.Write(sum);
while循环的写法:
int d = 0, sum = 0;
while (d <= 50)
{
int z = 0;
while (z <= 100)
{
int x = 0;
while (x <= 200)
{
if (d + z + x == 100 && d * 2 + z + x / 2 == 100)
{
Console.WriteLine("需要大马" + d + "头,中马" + z + "头,小马" + x + "头");
sum++;
}
x += 2;
}
z++;
}
d++;
}
Console.Write(sum);
百鸡百钱等问题同理。
数数问题
for写法:
int sum = 0;
for (; ; )
{
Console.Write("请输入一个100以内的整数:");
int a = int.Parse(Console.ReadLine());
if (a >= 0 && a <= 100)
{
for (int i = 1; i <= a; i++)
{
sum += i;
}
Console.WriteLine("1到" + a + "的和=" + sum);
break;
}
else
{
Console.WriteLine("您的输入有误,请重新输入!");
}
}
while写法:
int sum = 0;
int b = 0;
while (b == 0)
{
Console.Write("请输入一个100以内的整数:");
int a = int.Parse(Console.ReadLine());
if (a >= 0 && a <= 100)
{
int i = 1;
while (i <= a)
{
sum += i;
i++;
}
Console.WriteLine("1到" + a + "的和=" + sum);
break;
}
else
{
Console.WriteLine("您的输入有误,请重新输入!");
}
}
continue和break的区别:
continue是跳出本次循环,之后的继续;
break是终止循环。