第8周项目6-本月有几天(if~else~嵌套语句和switch语句)

来源:互联网 发布:java jdbc连接数据库 编辑:程序博客网 时间:2024/05/22 17:41
  1. /*  
  2.  * Copyright (c) 2014, 烟台大学计算机学院  
  3.  * All rights reserved.  
  4.  * 文件名称:test.cpp  
  5.  * 作    者:刘畅   
  6.  * 完成日期:2014年 10 月 16 日  
  7.  * 版 本 号:v1.0  
  8.  *  
  9.  * 问题描述:输入年份和月份,输出本月有多少天;
  10. * 输入描述: 输入年份year,月份month;
  11.  * 程序输出:输出本月?天。
  12. */
  13. (1)if~
  14. #include <iostream>using namespace std;int main(){    int year, month, x;    cout << "请输入年份和月份:";    cin >> year >> month;    if (year % 4 == 0)    {        if (year % 100 == 0)        {            if (year % 400 == 0)                x = 1;            else                x = 2;        }        else            x = 1;    }    else        x = 2;    if (month == 2)        if (x == 1)            cout << "本月有29天";        else            cout << "本月有28天";    else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)        cout << "本月有31天";    else if (month == 4 || month == 6 || month == 9 || month == 11)        cout << "本月有30天";    else        cout << "您的输入有错误,请重新输入\n";    return 0;}
  15.  
  16.  
  17. (2)switch语句
  18. #include <iostream>using namespace std;int main(){    int year,month;    cout<<"请输入年份和月份:";    cin>>year>>month;    if (month!=2)        switch (month)        {        case 1:        case 3:        case 7:        case 8:        case 10:        case 12:            cout<<"本月有31天";            break;        case 4:        case 6:        case 9:        case 11:            cout<<"本月有30天";            break;        }    else    {        if ((year%4==0&&year%100!=0)||year%400==0)            cout<<"本月有29天";        else            cout<<"本月有28天";    }    return 0;}

     
  19.  
  20. 运行结果:
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  

  27.  
  28.  
  29.  
  30.  
  31. 知识点总结:
  32. 对if~else~嵌套和switch语句开始有种得心应手的感觉,也开始试着多多运用& ,||, ! 这三种逻辑语句,还有"=="这个也在一次加深了理解。
  33.  
  34. 学习心得:
  35. haha~  贺老这周布置的任务已经全部完成,对if和switch有了初步的理解,虽然有点累,一下午都在写博客,但还是很开心啊大笑
  36. 学习编程最好的方式果然还是多多练习,加油!! 我要更加努力    才能带领我们团队更早地腾飞
0 0