c - 如何在 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;
}
解决方案
推荐阅读
- php - 正则表达式不匹配所有必需的字符。我做错什么了?
- node.js - 如何在我的 React 应用程序中使用我的 SQLite 查询?
- css - 通过 url() 使用剪辑路径时遇到问题
- javascript - 在使用 waypoints.js 时,如何绕过由于高度或边距而导致的 div 跳跃?
- jquery - 如何在 Jquery UI Datepicker 日期范围中再添加一天?
- android - 使用 iTextPDF 库标记支票
- r - 如何根据行最大值选择一列
- javascript - 反应:为什么我得到回调不是一个函数
- gatsby - 如何使用 gatsby-plugin-image 插件通过 GraphQL 查询图像
- reactjs - state 比 useEffect 落后一步