点击题号跳转

A5245 B3012 C3927 D1363 E3756

F1418 G4177 H5114 I3613 J4140

A.C++实验:日期相减回到顶部

题意

给一个日期求前num天的日期

题解

每次-1天,判断一下闰年就行,复杂度O(num)

需要重载+号和输出<<号

代码

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 struct Date{
 7     int y,m,d;
 8     Date(int _y=0,int _m=0,int _d=0):y(_y),m(_m),d(_d){}
 9 };
10 Date operator-(Date a,int num){
11     while(num--){
12         if(a.d>1)a.d--;
13         else if(a.d==1){
14             if(a.m>1){
15                 if(a.m==2||a.m==4||a.m==6||a.m==8||a.m==9||a.m==11){
16                     a.m--;a.d=31;
17                 }else if(a.m==3){
18                     if(a.y%400==0||(a.y%4==0&&a.y%100!=0)){
19                         a.m--;a.d=29;
20                     }else{
21                         a.m--;a.d=28;
22                     }
23                 }else{
24                     a.m--;a.d=30;
25                 }
26             }
27             else if(a.m==1){
28                 a.y--;a.m=12;a.d=31;
29             }
30         }
31     }
32     return a;
33 }
34 ostream& operator<<(ostream &out,Date s)
35 {
36     cout<<s.y<<"-"<<s.m<<"-"<<s.d;
37     return out;
38 }
A

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2021-11-01
  • 2021-12-24
  • 2021-06-02
  • 2021-09-16
  • 2021-05-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案