代码逻辑: Friday the Thirteenth (USACO)

标签 c

我是编码新手,我正在尝试为 USACO 发布的“十三号星期五”问题编写代码,该问题要求我们计算每月 13 日出现在星期日、星期一、星期二、星期三的频率,指定 N 年期间的星期四、星期五和星期六。测试的时间段为1900年1月1日至1900年12月31日+给定年数N-1,N。N为正数,不会超过400。

已知 1900 年 1 月 1 日是星期一。我们不应该使用任何内置函数。

我尝试用不同的方法解决这个问题(我认为这不是最好的方法)。我的代码(C 语言)如下:

#include<stdio.h>
int daysInMonth (int month, int year) 
{

/*
   30 should be returned if the months are Apr, June, Sept and Nov.
   31 should be returned in all other cases.
   29 should be returned if the month is Feb and the year is a leap year
 */ 

if (month == 1)     //Feb
    {
    if (year % 4 == 0 || (year % 100 != 0 && year % 400 == 0))  //leap year
        return 29;
    else
        return 28;

    }
switch (month)
    {
    case 3:
    case 5:
    case 8:
    case 10: return 30;
    default: return 31;

    }

}


void main () 
{
int month, year, n, i, noOfDays, start = 0, result[] = { 0, 0, 0, 0, 0, 0, 0 }, day = 0, daycheck = 1;
scanf ("%d", &n);
for (year = 1900; year <= 1900 + n - 1; ++year)
{
    for (month = 0; month < 12; ++month)
    {
        if (month == 0 && year == 1900) // to identify the first 13th and the day it falls on
        {
            while (daycheck != 13)
            {
                ++daycheck;
                day = (day + 1) % 7;

            }

            ++result[day];
        }

        else
        {
            if (month == 0) //If January, add the noOfDays of the prev. month i.e. December
                noOfDays = 31;

            else
              noOfDays = daysInMonth (month - 1, year);

            day += (noOfDays - 28); // Adding a multiple of 7 (here, 28) does not change the day
            day %= 7;

            ++result[day];

        }

    }

}

for (i = 0; i < 7; ++i)
    printf("%d ", result[(i + 5) % 7]); //Sat, Sun, Mon, Tue, Wed, Thu, Fri

}

对于输入 20,预期输出为 36 33 34 33 35 35 34。 然而,我的输出结果是 35 35 33 35 32 35 35。

尽管我的答案在预期输出的范围内,但我的逻辑有问题,导致其错误。

如果有人能指出错误,我将不胜感激。如果您能提出更好的方法来解决这个问题,我也将很高兴。我是计算机科学专业的学生,​​还没有详细了解算法。

最佳答案

您的闰年条件是错误的。

按如下方式更改闰年条件。

 int daysInMonth (int month, int year) 
    {
    if (month == 1)     //Feb
        {
    if (( year%400 == 0)|| (( year%4 == 0 ) &&( year%100 != 0)))
            return 29;
        else
            return 28;
        }

关于代码逻辑: Friday the Thirteenth (USACO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011958/

相关文章:

C 编程 - 将字符分配给盲文点

c - 如何在 C 中随机选择多个不同的数组元素?

c - CDT 中没有 javadoc 样式的注释?

java - 努力将 CRC-16 0x8408 从 C 反向转换为 Java

克隆 Eclipse 工作区的 Mercurial 存储库并在另一个位置重建

c - 调整 fseek 的读取数量

C: 在 printf 中为 float 的输出指定可变数量的小数点?

c - 我正在编写这个程序来查找单个数字中的两位数奇数,但我被困住了

c - 如何读取文本文件图像并将其保存到数组中?

c - 错误: conflicting types for 'functiono'