while语句按不同条件执行一个嵌入语句零次或多次。
格式:while(布尔类型表达式)嵌入式语句循环体
实例:输入两个数字,若和为100则继续输入,若不为100则退出游戏,最后的分数为输入100的次数。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace whilesample_10._13_
{
class Program
{
static void Main(string[] args)
{
int score = 0;
bool canContinue = true;
while(canContinue)
{
Console.WriteLine("Please input first number:");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("Please input second number:");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
int sum = x + y;
if(sum==100)
{
score++;
Console.WriteLine("Correct!{0}+{1}={2}",x,y,sum);
}
else
{
Console.WriteLine("Error!{0}+{1}={2}",x,y,sum);
canContinue = false;
}
}
Console.WriteLine("Your score is {0}",score);
Console.WriteLine("Game Over!");
}
}
}
程序结果为: