C# while循环
2024-08-28 04:10:39
一、简介
只要给定条件为true,C#的while循环语句会循环重新执行一个目标的语句。
二、语法
C# while的语法:
while(循环条件)
{
循环体;
}
三、执行过程
程序运行到while处,首先判断while所带的小括号内的循环条件是否成立,如果成立的话,也就是返回一个true,则执行循环体,执行完一遍循环体后,再次回到循环条件进行判断,如果依然成立,则继续执行循环体,如果不成立,则跳出while循环体。
在while循环当中,一般总会有那么一行代码,能够改变循环条件,使之终有一天不在成立,如果没有那么一行代码能够改变循环条件,也就是循环体条件永远成立,则我们将称之为死循环。
最简单死循环:
while(true)
{
}
四、特点
先判断,在执行,有可能一遍都不执行。
五、实例
1.向控制台打印100遍,下次考试我一定要细心.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Loops
{
class Program
{
static void Main(string[] args)
{
//需要定义一个循环变量用来记录循环的次数,每循环一次,循环变量应该自身加1
int i = 1;
while (i<=100)
{
Console.WriteLine("下次考试我一定要细心\t{0}", i);
//每循环一次,都呀自身加-,否则是死循环
i++;
}
Console.ReadKey(); }
}
}
输出结果
2.求1-100之间所有整数的和
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Loops
{
class Program
{
static void Main(string[] args)
{
//求1-100之间所有整数的和
//循环体:累加的过程
//循环条件:i<=100
int i = 1;
int sum = 0; //声明一个变量用来存储总和
while (i<=100)
{
sum += i;
i++;
}
Console.WriteLine("1-100之间所有整数的和为{0}",sum);
Console.ReadKey(); }
}
}
输出结果
最新文章
- WEB压力测试
- C#在excel中添加超链接
- display:flex 多栏多列布局
- SQL 启动服务方法
- sikuli实例
- Excel 代码
- 无废话C#设计模式系列文章
- import project后,出现Unable to get system library for the project
- UCOS 内存管理理解 创建任务
- C++<;algorithm>;中sort的比较函数写法(转)
- ASP.NET Core:CMD命令行+记事本 创建Console程序和Web Application
- Vuex 学习笔记
- 十三、实现Comparable接口和new Comparator<;T>;(){ }排序的实现过程
- Android内存优化之内存缓存
- headless&;unittest
- 树上差分——点差分裸题 P3128 [USACO15DEC]最大流Max Flow
- [转]TDD之Dummy Stub Fake Mock
- 温故而知新 前端日志上传新姿势 navigator.sendBeacon(信标)
- 安装VisualSVN Server 报错The specified TCP port is occupied
- ambassador 学习八 流量拷贝说明
热门文章
- Spring Cloud Bus介绍--Spring Cloud学习第七天(非原创)
- [日期工具分享][Shell]为特定命令依次传入顺序日期执行
- 多线程学习笔记(二) BackgroundWorker 和 ProgressChanged
- liteos错误处理(十一)
- Linux 初识Libevent网络库
- ubuntu 16.04中limit 修改
- 个人第2次作业:熟悉使用Git工具
- (day43)form表单、css
- Spring Cloud版本 version命名说明 (Edgware)
- html--前端jquery初识