通过例子进阶学习C++(一)年月日和一年中的第几天转换

 本文是通过例子学习C++的第一篇,通过这个例子可以快速入门c++相关的语法。

(1)输入年份year和第几天,输出月和日:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     int day,month,year,sum,leap;
 5     cin>>year>>sum;
 6     
 7     if((year%4==0 && year %100!=0) || (year %400==0)){
 8         leap = 1;
 9     }else leap = 0;
10     
11     if(sum<=31){
12         month = 1;
13         day = sum;
14     }else if(sum<=59){
15         month = 2;
16         day = sum - 31;
17     }else if(sum<=90){
18         month = 3;
19         day = sum - 59;
20     }else if(sum<=120){
21         month = 4;
22         day = sum - 90;    
23     }else if(sum<=151){
24         month = 5;
25         day = sum - 120;    
26     }else if(sum<=181){
27         month = 6;
28         day = sum - 151;
29     }else if(sum<=212){
30         month = 7;
31         day = sum - 181;
32     }else if(sum<=243){
33         month = 8;
34         day = sum - 212;
35     }else if(sum<=273){
36         month = 9;
37         day = sum - 243;
38     }else if(sum<=304){
39         month = 10;
40         day = sum - 273;
41     }else if(sum<=334){
42         month = 11;
43         day = sum - 304;
44     }else {
45         month = 12;
46         day = sum - 334;
47     }
48 
49     if(leap ==1 && month>=2){
50         if(day == 1){
51             month = month -1;
52             if(month==4 || month==6 || month==9 || month==11){
53                 day = 30;
54             } else{
55                 day  = 31;
56             } 
57         }else{
58             day = day -1;
59         }
60     }
61     cout<<month<<" "<<day<<endl;    
62     return 0;
63 }
View Code

通过该例子,可以学习:

  • c++程序的结构
  • 如何定义int型变量
  • 输入cin的用法
  • if语句、if条件“与或非”的组合
  • 输出语句cout
  • 运算符 +、-、*、/
  • 这里特别强调一下,在c++中“=”这个是赋值运算符不是数学上面的等号。数学上面的等号,在C++中是“==”。

(2)输入年、月、日,输出这一天是一年中的第几天:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     int day,month,year,sum,leap;
 5     cin>>year>>month>>day;
 6     switch(month){
 7        case 1: sum = 0; break;
 8        case 2: sum = 31; break;
 9        case 3: sum = 59; break;
10        case 4: sum = 90; break;
11        case 5: sum = 120; break;
12        case 6: sum = 151; break;
13        case 7: sum = 181; break;
14        case 8: sum = 212; break;
15        case 9: sum = 243; break;
16        case 10: sum = 273; break;
17        case 11: sum = 304; break;
18        case 12: sum = 334; break;
19        default: cout<<"输入错误,请重新输入!";break;
20     }
21     sum += day;
22     if((year%4==0 && year %100!=0) || (year %400==0)){
23         leap = 1;
24     }else leap = 0;
25     if(leap ==1 && month>2){
26         sum ++;
27     }
28     cout<<sum<<endl;    
29     return 0;
30 }
View Code

通过该例子,除了上面介绍的内容外,还可以学习:

  • switch语句
  • 复合运算符 +=、*=、/=、-=

posted @ 2020-01-11 20:37  siwei718  阅读(687)  评论(0编辑  收藏  举报