首页 > 解决方案 > 如何在 C 中创建一个变量,其值将根据当前日期发生变化?

问题描述

我正在尝试创建一个程序,用户可以在其中以月、日和年的格式输入他们的生日。我需要创建一个函数来根据当前日期计算用户的年龄(以天为单位)。我不能作为当前日期的用户,程序必须更新变量。我对C相当陌生。我没有太多...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct date
{
    int month;
    int day;
    int year;
};

int calcN(struct date d)
{
    int N;
    int f(struct date d);
    int g(int m);

    N = 1461 * f(d) / 4 + 153 * g(d.month) / 5 + d.day;

    if(d.year < 1700 || (d.year == 1700 && d.month < 3))
    {
        printf("Date must be after February 29th, 1700\n");

        return 0;
    }
    else if(d.year < 1800 || (d.year == 1800 && d.month < 3))
        N += 2;
    else if(d.year < 1900 || (d.year == 1900 && d.month < 3))
        N += 1;    

    return N;
}

int f(struct date d)
{
    if(d.month <= 2)
        d.year -= 1;

    return d.year;
}

int g(int m)
{
    if(m <=2)
        m += 13;
    else
        m += 1;
    
    return m;
}

int main(void)
{
    int calcN(struct date d);
    struct date d1, d2;
    int N1, N2;
    time_t t;

    time(&t);
    struct tm *now = localtime(&t);


    d1.month = now->tm_mon + 1;
    d1.day = now->tm_mday;
    d1.year = now->tm_year + 1900;

    printf("Today's date: %02i/%02i/%i\n", d1.month, d1.day, d1.year);

    N1 = calcN(d1);

    printf("Enter birthday (mm dd yyyy): ");
    scanf("%i%i%i", &d2.month, &d2.day, &d2.year);

    N2 = calcN(d2);

    if(N2 == 0)
        return 0;

    printf("Number of days since birthday: %i\n", N1 - N2);

    return 0;
}

标签: c

解决方案


推荐阅读