【发布时间】: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,所以它工作正常。但是当我给1或2时,输出是
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 31或number of day in month is 28?
【问题讨论】:
-
if (year%4==0) {cout <<"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