练习

本文提供两个实用的C++程序:一是判断输入年份是否为闰年;二是验证输入的年月日格式是否有效,包括对不同月份天数及闰年2月的特殊处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1编写程序判断一个年是否是闰年,是闰年返回ture,不是闰年返回false

#include<iostream>
using namespace std;
int year(long int x);
int main()
{
 long int a;
 cout<<"请输入一个年份:";
 cin>>a;
 if(year(a)==1)
  cout<<"false!"<<'\n';
 else
  cout<<"true!"<<'\n';
 return 0;
}
int year(long int x)
{
    int num;
 if(x%4==0)
 {
  if(x%100==0)
  {
   if(x%400==0)
    num=1;
   else
    num=0;
  }
  else   num=1;
 }
 else     num=0;
    return (num);
}

(2)编写一个程序判断输入的年月日是否合法。输入例如 2012  2  12形式

#include<iostream>
using namespace std;
int year(long int x)
{
    int num;
 if(x%4==0)
 {
  if(x%100==0)
  {
   if(x%400==0)
    num=1;
   else
    num=0;
  }
  else   num=1;
 }
 else     num=0;
    return (num);
}
int main()
{
 long int a;
 int b,c;
 cout<<"请输入一个日期:";
 cin>>a>>b>>c;
 if(a<=0)
     cout<<"该日期格式不合法";
 else
 {
  if(b<1||b>=12)
   cout<<"该日期格式不合法";
  if(b==2)
  {
   if(year(a)==1)
   {
    if(c<1||c>29)
     cout<<"该日期格式不合法";
    else  cout<<"该日期格式合法";
   }
   else
   {
    if(c<1||c>28)
     cout<<"该日期格式不合法";
                else  cout<<"该日期格式合法";
   }
  }
  if(b==1||b==3||b==5||b==7||b==8||b==10||b==12)
  {
   if(c>31) cout<<"该日期格式不合法";
            else  cout<<"该日期格式合法";
  }
  if(b==4||b==6||b==9||b==11)
  {
   if(c>30)  cout<<"该日期格式不合法";
            else  cout<<"该日期格式合法";
  }
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值