我已经使用嵌套for循环完成了这个,但是我也想知道如何使用while循环执行此操作。我已经有了这个
int j = 10;
int k = 0;
while (j > 0)
{
if (k <= j)
{
Console.Write("* ");
Console.WriteLine();
}
j--;
} Console.WriteLine();
它打印出一排星星(*)。我知道内部循环必须引用外部循环,但我不知道如何在while语句中执行此操作。
答案 0 :(得分:4)
由于这已经使用嵌套的for循环完成,因此转换为while循环是直截了当的。 (如果使用相同的算法,2个for循环将导致2个while循环,而不是1个。)
这for-loop:
for (initializer; condition; iterator) {
body;
}
等同于这个while循环:
initializer;
while (condition) {
body;
iterator;
}
Nit:关于变量生命周期实际上有a breaking change in C# 5使得上述不太完全相同(在C#5 +中),但这是语言规范的另一个主题尚未最终确定,只影响闭包中绑定的变量。
答案 1 :(得分:3)
for循环可以与while循环轻微互换。
// Height and width of the triangle
var h = 8;
var w = 30;
// The iterator variables
var y = 1;
var x = 1;
// Print the tip of the triangle
Console.WriteLine("*");
y = 1;
while (y++ <h) {
// Print the bit of left wall
Console.Write("*");
// Calculate length at this y-coordinate
var l = (int) w*y/h;
// Print the hypothenus bit
x = 1;
while (x++ <l-3) {
Console.Write(" ");
}
Console.WriteLine("*");
}
// Now print the bottom edge
x = 0;
while (x++ <w) {
Console.Write("*");
}
输出:
*
* *
* *
* *
* *
* *
* *
* *
******************************
答案 2 :(得分:1)
这会产生类似三角形的东西:
int x = 1;
int j = 10;
int k = 0;
while (j > 0)
{
if (k <= j)
{
Console.Write("* ");
}
if (j >= 1)
{
int temp = x;
while (temp >= 0)
{
Console.Write(" ");
temp--;
}
x = x + 1;
Console.Write("*");
}
Console.WriteLine();
j--;
}
Console.WriteLine();
double f = Math.Round(x * 1.5);
while (f != 0)
{
Console.Write("*");
f--;
}
答案 3 :(得分:0)
class x
{
static void Main(string[] args)
{
int i, j;
for ( i=0;i<10;i++)
{
for (j = 0; j < i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}