【问题标题】:Usaco. Friday the thirteen. What is wrong with my code?乌萨科。十三号星期五。我的代码有什么问题?
【发布时间】:2014-01-20 20:14:06
【问题描述】:

我已经为 USACO 任务制作了一个程序,但现在我无法弄清楚为什么我得到了错误的答案,我一直在思考为什么会这样,但仍然没有弄清楚。有什么问题?

任务是计算 13 号落在星期六、星期日、星期一、星期二、...、星期五的次数。测试的年份是 1900 年,最后一年在 txt 文件中给出。

而不是这个答案:36 33 34 33 35 35 34

我收到:34 33 33 33 36 36 35

非常非常非常感谢你的帮助,我真的很感谢你的时间和你的帮助:)

#include<iostream>
#include<fstream>

using namespace std;

int weekDayCount(int days, int weekDays[], int & currentWeekDay)
{

for(int day = 1; day <= days; day++)
{      
    if(day == 13)
    {
        weekDays[currentWeekDay]++;
    }

    currentWeekDay++;

    if(currentWeekDay == 7) currentWeekDay = 0;
}
}

int main()
{
int currentWeekDay = 0;
int years;

ifstream in("friday.in");

in >> years;

in.close();

int weekDays[7] = {0};

for(int y = 1900; y <= (1900 + years) - 1; y++) // Years
{
    cout << y << endl;

    for(int m = 1; m <= 12; m++) // Months
    {
        if(m == 11 || m == 2 || m == 10 || m == 8) // 30 days
        {
            weekDayCount(30, weekDays, currentWeekDay);
        }
        else if(m == 5) // February
        {
            if(y % 100 != 0 && y % 4 == 0) // If a leap year - 29 days
            {
                weekDayCount(29, weekDays, currentWeekDay);
            }
            else if(y % 100 == 0 && y % 400 == 0) // If a century leap year
            {
                cout << "Leap century: " << y << endl;
                weekDayCount(29, weekDays, currentWeekDay);
            }
            else // 28 days
            {
                weekDayCount(28, weekDays, currentWeekDay);
            }
        }
        else // Else 31 days
        {
            weekDayCount(31, weekDays, currentWeekDay);
        }
    }
}

cout << "Result" << endl;

 cout << weekDays[5] << " " << weekDays[6] << " " << weekDays[0] << " " << weekDays[1] << " " << weekDays[2] << " " << weekDays[3] << " " << weekDays[4] << endl;
}

【问题讨论】:

  • 二月的第五个月怎么样?
  • 还有,m==2怎么能有30天呢?
  • 我建议你学习使用调试器。它会在这些情况下为您提供帮助。
  • 你是说有 30 天的月份是 11 月、2 月、10 月和 8 月?
  • 你真的应该找个时间看看日历。严重地。在 12 个月中,你错了 7 个月。

标签: c++ logic task days


【解决方案1】:

您的月份比较不正确。

二月是第二个月,不是第五个月。
作为第二个月,它没有 30 天(至少自从我活着以来)。

您可能想要交换这些常量。

【讨论】:

  • 哦,我明白了!这么愚蠢的错误,我只是查错了日历。非常感谢!
猜你喜欢
  • 2015-03-11
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2011-07-28
相关资源
最近更新 更多