0
点赞
收藏
分享

微信扫一扫

c#for循环结构


前面几种讲过三个循环一种,最近确实事情忙,忘了写博客多多谅解哈!回归正题,今天我们就一起来学习c#的for循环!

接下来我们判断一下for循环和while循环有什么区别

1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp19
{
internal class Program
{
static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("给我点赞都是帅哥");
i++;
}
}
}
}

接下来我们来用for循环写循环

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp19
{
internal class Program
{
static void Main(string[] args)
{
for(int i = 0;//定义初始变量 i <= 5;//循环条件 i++//计数)
{
Console.WriteLine("给我点赞都是大帅哥");
}
}
}
}

虽然循环结果都是一样,但是for'循环明显要比while循环简便点

在for循环中的语法组成for(初始值,循环条件,计数){

输出语句;

}

注意:for循环没写完一个条件需要加分号,不然会报错哦!

2.for循环的使用

接下来用一个案例来了解for循环的使用方式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp19
{
internal class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 200; i++)
sum += i;
{
Console.WriteLine("1到100的自然数之和:"+sum);
}
}
}
}

for循环只要按两下tab建就可以插入循环结构哦!

先定义一个sum存储值,然后插入for循环分别输入值,循环条件,计数,然后把i的值赋给sum,然后就输出1到100的自然数之和。千万记住如果不加i++的话会进入死循环,记得写到最后的话一定要加个i++;

接下来我们实践一个案例判断该日期对应年份是第几天

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp19
{
internal class Program
{
static void Main(string[] args)
{
int year, month, date;//分别定义三个变量来表示年月日
int day = 0;//天数
//接受用户输入的年月日
Console.WriteLine("请输入日期:");
year = int.Parse(Console.ReadLine());
month = int.Parse(Console.ReadLine());
date = int.Parse(Console.ReadLine());
//使用循环结构来加每月的天数
for(int i = 0; i < month; i++)
//使用switch结构,实现每月的计算
{
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day += 30;
break;
case 4:
case 6:
case 9:
case 11:
day += 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
day += 29;
else
day += 28;
break;

}
day += date;
Console.WriteLine("{0}年{1}月{2}日是当年第{3}天",year,month,date,day);
}


}
}
}

这就是for的知识,喜欢的朋友多多三连,嘻嘻!

举报

相关推荐

0 条评论