本示例的FOR循环创建一个Mandelbrot图像。
代码如下 |
复制代码 |
using System;
namespace a
{
class Program
{
public static void Main(string[] args)
{
double realCoord,imagCoord;
double realTemp,imagTemp,realTemp2,arg;
int iterations;
for (imagCoord=1.2;imagCoord>=-1.2;imagCoord-=0.05)
{
for(realCoord=-0.6;realCoord<=1.77;realCoord+=0.03)
{
iterations=0;
realTemp=realCoord;
imagTemp=imagCoord;
arg=(realCoord*realCoord)+(imagCoord*imagCoord);
while((arg<4)&&(iterations<40))
{
realTemp2=(realTemp*realTemp)-(imagTemp*imagTemp)-realCoord;
imagTemp=(2*realTemp*imagTemp)-imagCoord;
realTemp=realTemp2;
arg=(realTemp*realTemp)+(imagTemp*imagTemp);
iterations+=1;
}
switch (iterations % 4)
{
case 0:
Console.Write(".");
break;
case 1:
Console.Write("o");
break;
case 2:
Console.Write("0");
break;
case 3:
Console.Write("@");
break;
}
}
Console.Write("n");
}
Console.ReadKey();
}
}
}
|
循环结构之DO语句
循环结构之DO语句,根据布尔值的测试结果,执行相应代码,DO语句至少执行一次。
代码如下 |
复制代码 |
using System;
namespace a
{
class Program
{
public static void Main(string[] args)
{
double balance,interestRate,targetBalance;
Console.WriteLine("What is your current balance?");
balance=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What is your current annual interest rate (in %)?");
interestRate= 1+Convert.ToDouble(Console.ReadLine())/100.0;
Console.WriteLine("What balance would you like to have?");
targetBalance=Convert.ToDouble(Console.ReadLine());
int totalYears=0;
do
{
balance*=interestRate;
++totalYears;
}
while(balance
Console.WriteLine("In {0} year {1} you'll have a balance of {2}.",totalYears,totalYears==1?"":"s",balan00ce);
Console.ReadKey();
}
}
}
|
总结
DO语句在循环时不管条件是否成立它至少执行一次,页for循环语句如果条件不成立一次不执行了。