【问题标题】:Return number of days in a given month of a given year返回给定年份的给定月份的天数
【发布时间】:2016-09-02 02:43:39
【问题描述】:

我写了一个程序,给定月份和年份,返回该月的天数:

#include <iostream.h>
#include <conio.h>
void main() {
  clrscr();
  int month, year, i;
  cout << "give the year \n";
  cin >> year;
  cout << "give the month\n";
  cin >> month;
  for (i = 1; i <= 12; i++) {
    i = month;
    switch (month) {
      case 1:
        cout << "number of day in month is 31\n";
        break;
      case 2:
        if (year % 4 == 0) {
          cout << "the number of days is 29 \n";
        } else {
          cout << "the number of days is 28 \n";
        }
        break;
      case 3, 5, 7, 8, 10, 12:
        cout << "the number of days is 31 \n";
        break;
      default:
        cout << "the number of days is 30 \n";
        return;
    }
  }
  return;
}

当我给出月份编号3 时,它返回the number of days is 31,所以它工作正常。但是当我给12时,输出是

number of day in month is 31
number of day in month is 31
number of day in month is 31
.
.
.
.

如果情况是2,我怎样才能让它只返回number of day in month is 31number of day in month is 28

【问题讨论】:

  • if (year%4==0) {cout &lt;&lt;"the number of days is 29 \n";}。如果(year%100)==0 不是,除非(year%400)==0 也是如此。请参阅en.wikipedia.org/wiki/Leap_year除能被 100 整除的年份外,每个能被 4 整除的年份都是闰年,但如果它们能被 400 整除,则这些百年年份就是闰年。例如, 1700、1800 和 1900 年不是闰年,但 2000 年是。
  • 但脚本中的 (year%4==0) 不是 %100
  • @AndrewHenle 如何解决案例 1 和 2 中的重复问题
  • @AymenDerradji:这在 2100 年是错误的,这不是闰年。
  • @AymenDerradji:没有“最好的”。有对也有错。能被 4 整除的年份是闰年。例外:1900、2100、2200、2300、2500 但不是 2000 和 2400。“正确”检查三个条件。按照 Andrew 写的内容编写单元测试。

标签: c++ for-loop switch-statement


【解决方案1】:

懒惰的方式:

#include <ctime>
static int GetDaysInMonthOfTheDate(std::tm curDate)
{
    std::tm date = curDate;
    int i = 0;
    for (i = 29; i <= 31; i++)
    {
        date.tm_mday = i;
        mktime(&date);

        if (date1->tm_mon != curDate.tm_mon)
        {
            break;
        }
    }
    return i - 1;    
}

【讨论】:

    【解决方案2】:

    不要重复计算/不要使用循环。正确使用 switch case 语法。

    而且你的闰年计算是错误的。应该是这样的:

    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
        cout << "the number of days is 29 \n";
    }
    else {
        cout << "the number of days is 28 \n";
    }
    

    如果能被 4 整除但不能被 100 整除能被 400 整除

    ,则一年为闰年

    【讨论】:

      【解决方案3】:

      你有一个循环,i 从 1 运行到 12。

      在你做的那个循环内

      switch (month)
      

      但你可能是说

      switch (i)
      

      否则你只是重复同样的计算 12 次。

      【讨论】:

      • 所以我只会用不带for的switch来做
      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多