0

所以我必须编写一个从 1.1.1 开始计算天数的程序此外,我必须一直使用公历(即使它没有从 1.1.1 开始使用)无论如何,这是我写的,但我是肯定有一些错误:

#include <stdio.h>
int main()

{
    int d, m, r;
    printf("Podaj dzien, miesiac i rok\n");
    scanf("%d %d %d", &d, &m, &r);
    printf("%d", iledni(d, m, r));
    return 0;
}

int iledni(int d, int m, int r)
{
    int dni,x;
    int msc[12]={0,31,59,90,120,151,181,212,243,273,304,334};
    dni=r*365+msc[m-1]+d-1;
    dni=dni+(int)((r-1)/4)-(int)((r-1)/100)+(int)((r-1)/400);
    if (m>2 && r%4 == 0 && r%100 != 0 || r%400 == 0)
        dni=dni+1;
    return dni;
}

我的下一个任务是编写一个计算从我出生到当前日期的天数的函数,我不确定应该如何输入数据,所以现在我假设它只是用 int main() 编写的,所以我只需要更改 iledni功能,但我有一些问题,确切地说是错误的结果,不知道如何修复它><

#include <stdio.h>
int main()
{
    int d=17, m=8, r=2013;
    int du=25, mu=11, ru=1994;
    printf("%d", iledni(d, m, r, du, mu, ru));
    return 0;
}

int iledni(int d, int m, int r, int du, int mu, int ru)
{
    int dni,x;
    int msc[12]={0,31,59,90,120,151,181,212,243,273,304,334};
    int mscdodni[12]={31,28,31,30,31,30,31,31,30,31,30,31};
    dni=(r-ru)*365+msc[m-1]-msc[mu]+d-1+(mscdodni[mu-1]-du);
    for (ru=1994; ru<=r; ru++)
        {
        if (ru%4 == 0 && ru%100 != 0 || ru%400 == 0)
            dni=dni+1;
        }
return dni;
}

告诉我是否应该解释任何行,我也是初学者,所以如果我写的任何东西没有意义,我很抱歉,我对 C 或整个编程不太了解。

4

1 回答 1

0

Don't know if the following could be of any help, at least for the second part of your requirement (get the number of days from your birthdate to the current date):

This function will return the number of days from 1900-1-1:

int countDaysFrom1900(int y, int m, int d) {
    // The sum of days, equivalent to your msc array
    int days[] = {0, 31, days[1] + 28, days[2] + 31, days[3] + 30, days[4] + 31, days[5] + 30, days[6] + 31, days[7] + 31, days[8] + 30, days[9] + 31, days[10] + 30, days[11] + 31};

    // Offset the day value if the year is a leap year 
    // The: "(!(y % 400) || ((y % 100) && !(y % 4)))" thing is checking the leap year
    int offset = m > 2 && (!(y % 400) || ((y % 100) && !(y % 4))) ? 1 : 0;

    // Calculate the number of transcurred days 
    return y -= 1901, ((y + 1) * 365 + (y / 4) - (y / 100) + ((y + 1900) / 400) - 4 + days[m - 1] + offset + d - 1);
}

Here is an usage example:

int main() { 
    std::cout << countDaysFrom1900(1900, 1, 1) << std::endl;
    std::cout << countDaysFrom1900(1900, 1, 2) << std::endl;
    std::cout << countDaysFrom1900(1901, 1, 1) << std::endl;
    std::cout << countDaysFrom1900(2013, 10, 13) << std::endl;

    // Some birthdate
    int daysFromBirthdate = countDaysFrom1900(1982, 4, 27);
    int currentDate = countDaysFrom1900(2013, 10, 13);

    std::cout << "There are " << (currentDate - daysFromBirthdate) << " days from birthdate" << std::endl;
    return 0;
}

Prints:

0
1
365
41558
There are 11492 days from birthdate
于 2013-10-14T00:50:12.437 回答