• C++ 日期推算


    【问题描述】

    设计一个程序用于向后推算指定日期经过n天后的具体日期。

    【输入形式】

    • 输入为长度为8的字符串str和一个正整数n,str前四位表示年份,后四位表示月和日。

    【输出形式】

    • 当推算出的年份大于4位数时,输出"out of limitation!",否则输出8位的具体日期。

    【样例输入1】

    00250709 60000

    【样例输出1】

    01891017

    【样例输入2】

    19310918 5080

    【样例输出2】

    19450815

    【样例输入3】

    99980208 999

    【样例输入3】

    out of limitation!

    【样例说明】

    • 日期的表示必须8位数,年月日不足长度需要添加前缀字符'0'。

    • 注意闰年和平年的2月份天数不同。

    • 注意判断输出信息是否符合要求。

     【完整代码如下】

    1. #include
    2. #include
    3. using namespace std;
    4. class Calculate
    5. {
    6. public:
    7. Calculate(int years,int months,int days,int ns):year(years),month(months),day(days),n(ns)
    8. {
    9. }
    10. bool Judge();//判断是否为闰年
    11. void AddOne();
    12. void AddDay();
    13. void show();
    14. private:
    15. int year;
    16. int month;
    17. int day;
    18. int n;
    19. };
    20. bool Calculate::Judge()
    21. {
    22. if((year%400==0)||(year%100!=0&&year%4==0))
    23. return true;
    24. else
    25. return false;
    26. }
    27. void Calculate::AddOne()
    28. {
    29. if((month==1||month==3||month==5||month==7||month==8||month==10)&&(day==31))
    30. {
    31. day=1;
    32. month+=1;
    33. }
    34. else if((month==4||month==6||month==9||month==11)&&(day==30))
    35. {
    36. day=1;
    37. month+=1;
    38. }
    39. else if(month==12&&day==31)
    40. {
    41. day=1;
    42. month=1;
    43. year+=1;
    44. }
    45. else if(month==2&&day==29&&Judge())
    46. {
    47. day=1;
    48. month+=1;
    49. }
    50. else if(month==2&&day==28&&!Judge())
    51. {
    52. day=1;
    53. month+=1;
    54. }
    55. else
    56. {
    57. day+=1;
    58. }
    59. }
    60. void Calculate::AddDay()
    61. {
    62. for(int i=0;i
    63. {
    64. AddOne();
    65. }
    66. if(year>9999)//判断推算出的年份大于4位数
    67. {
    68. cout<<"out of limitation!"<
    69. }
    70. else
    71. {
    72. show();
    73. }
    74. }
    75. void Calculate::show()
    76. {
    77. cout<
    78. }
    79. int main()
    80. {
    81. string str;
    82. int n;
    83. cin>>str;
    84. cin>>n;
    85. //把字符串里的日期信息转化为数字,方便后面的运算
    86. int year = 1000 * (str[0] - 48) + 100 * (str[1] - 48) + 10 * (str[2] - 48) + (str[3] - 48);
    87. // cout<
    88. int month = 10 * (str[4] - 48) + (str[5] - 48);
    89. /// cout<
    90. int day = 10 * (str[6] - 48) + (str[7] - 48);
    91. // cout<
    92. Calculate t(year,month,day,n);
    93. t.AddDay();
    94. return 0;
    95. }

  • 相关阅读:
    Java网络编程:Socket与NIO的高级应用
    Java学习----集合1
    python列表操作和方法
    PT_数字特征/常见分布的期望和方差
    【Flutter】混合开发之Flutter预加载解决第一次加载页面缓慢问题
    Lambda表达式常见用法(提高效率神器)
    Ubuntu终端Terminator的安装
    chatGPT教你算法(1)——常用的排序算法
    Ubuntu openssh-server 离线安装
    GPT-4科研实践:数据可视化、统计分析、编程、机器学习数据挖掘、数据预处理、代码优化、科研方法论
  • 原文地址:https://blog.csdn.net/weixin_74287172/article/details/134470091