计算时间练习
static void Main(string[] args)
{
//练习编程实现计算几天(如46天)是几周零几天
Console.WriteLine("请输入要计算的天数");
string strDays=Console.ReadLine();
int day=Convert.ToInt32(strDays);//字符串转int类型
int week=day/7;
int lastDay=day%7;
Console.WriteLine("{0}天是{1}周零{2}天",day,week,lastDay);
Console.ReadKey();
//编程实现输入多少秒转化为几天几小时几分钟几秒
Console.WriteLine("请输入要转换的秒数!!!");
int seconds=Convert.ToInt32(Console.ReadLine());
int day=seconds/86400;//求天数
int secs=seconds%86400;//求剩余的秒数
int hours=secs/3600;//求剩余的小时数
secs = secs % 3600; //求完小时数后剩余的秒数
int mins=secs/60;//求分钟数
secs=secs%60;//求完分钟后剩余的秒数
Console.WriteLine("{0}秒是{1}天{2}小时{3}分钟{4}秒", seconds,day,secs,hours,mins);
Console.ReadKey();
}
交换变量
//第一种声明一个第三方变量
int n1=10;
int n2=20;
int temp=n1;
n1=n2;
n2=temp;
Console.WriteLine("{0}\t{1}",n1,n2);
Console.ReadKey();
//第二种不使用第三方变量
int i=10;
int j=20;
i=i-j;//i=-10,j=20
j=i+j;//i=-10,j=10
i = j - i;//j=10 i=20
Console.WriteLine("交换后,i的值是{0},j的值是{1}", i, j);
Console.ReadKey();
判断是否为闰年
//第一种使用逻辑运算符
Console.WriteLine("请输入一个年份!!");
int year=Convert.ToInt32(Console.ReadLine());
//判断闰年的思路是:1是年份能被400整除 2是年份能够被4整除但不能被100整除
bool b = (year % 400 == 0)||(year % 4 == 0 && year % 100 != 0);
Console.WriteLine(b);
Console.ReadKey();
//第二种使用三元表达式
bool result=(year % 400 == 0)||(year % 4 == 0 && year % 100 != 0)?ture:false
判断年份某个月是几天
static void Main(string[] args)
{
// 请用户输年份,再输入月份,输出该月的天数.(结合之前如何判断闰年来做)
Console.WriteLine("请输入一个年份");
try
{
int year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入一个月份");
try
{
int month = Convert.ToInt32(Console.ReadLine());
if (month >= 1 && month <= 12)
{
int day = 0;//存储天数
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{
day = 29;
}
else
{
day = 28;
}
break;
default:
day = 30;
break;
}//switch
Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
}//if的结束
else
{
Console.WriteLine("月份必须在1~12月之间,程序退出!!!");
}
}//try月份结束
catch
{
Console.WriteLine("月份输入有误,程序退出");
}
}//try年份结束
catch
{
Console.WriteLine("年份输入有误,程序退出");
}
Console.ReadKey();
}