我编写了一个程序,根据月份编号和年份,返回该月份的天数:
#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
.
.
.
.
如果案例为number of day in month is 31
,如何才能让它返回number of day in month is 28
或2
?
答案 0 :(得分:2)
你有一个i
从1到12运行的循环。
在你的循环中你做
switch (month)
但你可能意味着
switch (i)
否则你只是重复12次相同的计算。
答案 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整除
答案 2 :(得分:0)
懒惰的方式:
#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;
}