1、程序循环
(1)良性循环和恶性循环
良性循环的条件:
I.总是初始化循环的初始条件。
II.提供一个测试表达式来决定是否需要进行循环的下一次迭代。
III.更改控制循环变量的当前状态。
无限循环:通常是无意中产生的循环,并且会挂起系统。每当编写设计程序循环的代码,最好在运行前保存代码。
(2)for循环
在文章结尾给出本章的示例程序。
定义几个有效的变量,通过相关的代码来确保用户界面对象的输入数据的安全。
利用tryparse方法来验证输入数据是否是正确数据。
格式化字符串数据:Format()方法
buff = string.Format("{0,5}{1,20}",i,i*i);
在平方表的程序编写中,利用了如上的代码编写,{0,5}是其第一个参数,在5个字符的字段中右对齐。
{1,20}表示第二个参数格式化为在20个字符的字段中右对齐。
以下列出相应格式选项字符串:
{0} “kate” |kate|
{0.15} “kate” | kate|
{0,-15} “kate” |kate |
{0,15:C} 5.10 | $5.10|
{0,mm}
{0,5:hh}
{0,15:hh mm}
{0,dddd MMMM}
如果字体和列不对齐,那么就是使用默认字体的原因。
lstOutput.Items.Add(buff);
在处理字体之后,将buff中的数据添加到lstoutput中。
(3)while循环
while循环的良性三个条件仍然是在for的规则,
不过在while中限制循环的条件被分散了。
(4)do-while程序循环
其类似于while循环。只有一个不同之处:do-while至少执行一次循环语句块。
示例程序:给定一个最大值,在这个范围内生成随机数,观察需要多少次循环才能生成两个完全相同的随机数:
private void btnStart_Click(object sender, EventArgs e)
{
bool flag;
int counter;
int max;
int last;
int current;
Random randomNumber = new Random();
flag = int.TryParse(txtMax.Text,out max);
if (flag == false)
{
MessageBox.Show("Digit characters only","Input Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
txtMax.Focus();
return;
}
counter = 0;
last = (int)randomNumber.Next(max);
do{
current = randomNumber.Next(max);
if (last == current)
{ break; }
counter++;
last = current;
}while(counter<MAXITERATIONS);
if (counter < MAXITERATIONS)
{
lblAnswer.Text = "It took " + counter.ToString() + " passes to match";
}
else {
lblAnswer.Text = "no back-to-back match";
}
}
对以上程序的简析:
这里使用符号常量MAXITERATIONS来对循环的次数进行约束。
Random的类方法next产生0~MAX-1之间的随机值。
在一个循环程序块中执行break,都会将程序控制发送给循环语句块的右侧大括号后的第一个语句。
(5)Continue循环
保持程序控制在循环中,从而判断是否授权执行下一次循环。
附加代码:平方表程序,打出一个平方表
using System;
using System.Windows.Forms;
public class frmMain : Form
{
private Label label1;
private Label label2;
private Button btnCaculate;
private Button btnClear;
private Button btnClose;
private TextBox txtStart;
private TextBox txtEnd;
private ListBox lstOutput;
#region Windows code
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnCaculate