我是靠谱客的博主 自信大炮,这篇文章主要介绍C++选择结构程序设计(总),现在分享给大家,希望可以做个参考。

一下用到的例子都会与闰年相关,所以有必要解释下关于闰年的一些知识ヾ(◍°∇°◍)ノ゙

闰年分为普通闰年(能被4整除但不能被100整除的年份)和世纪闰年(能被400整除的年份

例题1:输入一个年份,判断是否为闰年

分析:

  • 闰年的年份可以被4整除而不能被100整除,或者能被400整除
  • 输入年份存放在year变量中,如果表达式(year%4==0&&year%100!=0)||(year%400==0)的值为true,则为闰年,否则不是闰年

1.if语句

#include <iostream>
using namespace std;
void main()
{int year;
cout<<"Enter the year:";
cin>>year;
if((year%4==0&&year%100!=0)||(year%400==0))//判断是否为闰年
	cout<<year<<" is a leap year"<<endl;
else
	cout<<year<<" is not a leap year"<<endl;
}

2.if-else语句(嵌套选择结构需要着重理解并熟练运用)

#include <iostream>
using namespace std;
void main()
{
//变量声明,leap起标识作用
	int year,leap;
//输入一个年份
	cout<<"please enter year:"<<endl;
	cin>>year;
if(year%4==0)
{
	if(year%100!=0)
		leap=1;
	else
		if(year%400==0)
			leap=1;
		else
			leap=0;
}
else
	leap=0;
if(leap)//相当于leap!=0或leap==1
	cout<<year<<" year is leap year"<<endl;
else
	cout<<year<<" year is not leap year"<<endl;
}//整个程序运用了布尔类型去设计

当然对于多路分支结构的实现,除了if语句嵌套方式实现,也可以采用开关语句(switch语句)实现  ( ̄▽ ̄)~*

有关switch语句的详细解读:

https://blog.csdn.net/bruce_0712/article/details/72808456

例题二:输入某年某月某日,判断这一天是这一年的第几天

说明:接下来给出的两种方法都是先确定月份,再判断是否为闰年。也可以先判断年份,再判断月份。(๑*◡*๑)

法一:

#include <iostream>
using namespace std;
void main()
{
	int year,month,day,num=0;
	cout<<"请分别输入年月日:";
	cin>>year>>month>>day;
	switch(month)//不需要用break,要一直执行下去
	{
	case 12:num+=30;
	case 11:num+=31;
	case 10:num+=30;
	case 9:num+=31;
	case 8:num+=31;
	case 7:num+=30;
	case 6:num+=31;
	case 5:num+=30;
	case 4:num+=31;
	case 3:num+=28;
	case 2:num+=31;
	case 1:num+=0;
	}
	num=num+day;
	if(month>2)
	if((year%4==0&&year%100!=0)||(year%400==0))
		num++;//num++即num=num+1
	cout<<"这是"<<year<<"年的第"<<num<<"天"<<endl;
}

法二:

#include <iostream>
using namespace std;
void main()
{
	int day,month,year,sum,leap;
	cout<<"Please input year,month,day:n";
	cin>>year>>month>>day;
	switch(month)//先计算某月以前月份的总天数
	{
	case 1:sum=0;break;
	case 2:sum=31;break;
	case 3:sum=59;break;
	case 4:sum=90;break;
	case 5:sum=120;break;
	case 6:sum=151;break;
	case 7:sum=181;break;
	case 8:sum=212;break;
	case 9:sum=243;break;
	case 10:sum=273;break;
	case 11:sum=304;break;
	case 12:sum=334;break;
	default:cout<<"data error";break;
	}
	sum=sum+day;//再加上某天的天数
	if(year%400==0||(year%4==0&&year%100!=0))//判断闰年
		leap=1;
	else
		leap=0;
	if(leap==1&&month>2)//是闰年且月份大于2,总天数应加一天
		sum++;
	cout<<year<<" year "<<month<<" month "<<day<<" day "<<"是这一年的第"<<sum<<"天"<<endl;
}

最后,为了更好理解switch结构呢,再给一个实例(๑¯∀¯๑)

例题三:将百分制化为五分制

#include <iostream>
using namespace std;
void main()
{
	int old_grade,new_grade;
	cout<<"please input old grade:";
	cin>>old_grade;
	switch(old_grade/10)
	{
	case 10:
	case 9:new_grade=1;break;
	case 8:new_grade=2;break;
	case 7:new_grade=3;break;
	case 6:new_grade=4;break;
	default:new_grade=5;
	}
	cout<<new_grade<<endl;
}

 

最后

以上就是自信大炮最近收集整理的关于C++选择结构程序设计(总)的全部内容,更多相关C++选择结构程序设计(总)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(168)

评论列表共有 0 条评论

立即
投稿
返回
顶部