我正在尝试用来自用户的这两个数据集在C中编写程序。年份:[范围1901-2099]和日期:[范围1-366]我需要一个公式来计算MM / DD / YYYY格式的日期。还有一件事。没有IF / ELSE声明。不允许和/或大于或小于。
答案 0 :(得分:2)
您可以使用嵌套的switch case来避免使用if-else。
简而言之,逻辑可以如下:
isLeapYear = year % 4
Switch(isLeapYear)
Case 0: {
first_bucket = days/4
Switch(first_bucket)
{
Case 0: {
days_left = days % 100
second_bucket = days / 50;
// ...
// ...
}
Case 1, 2, 3: {
// Similar logic for non-leap year
// ...
}
答案 1 :(得分:2)
您可以在没有任何流控制语句(如果,切换)的情况下执行此操作,也无需自行执行闰年计算。获取与所需年份的1月1日对应的时间戳。然后,您可以在时间戳上使用单个添加来获取正确的日期,并将时间戳转换为您想要的任何格式。
我会提供代码,特定的函数名称并解释你需要添加到时间戳的内容,但由于这显然是一个功课问题,我不会。如果有人在两周内提醒我(即当作业的最后期限很可能结束时),我会很乐意发布示例代码。
答案 2 :(得分:1)
如果允许使用库函数(我怀疑),我会这样做(lazy lego):
#define _XOPEN_SOURCE /* glibc2 needs this for strptime */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
int to_date(
char * date,
const size_t size,
const char * fmt,
const short unsigned int day_of_year,
const short unsigned int year)
{
char buffer[16] = "";
sprintf(buffer, "%hu %hu", day_of_year, year);
{
struct tm t = {0};
char * presult = strptime(buffer, "%j %Y", &t);
if ((NULL == presult) || ('\0' != *presult))
{
errno = EINVAL;
return -1;
}
strftime(date, size, fmt, &t);
}
return 0;
}
int main(int argc, char ** argv)
{
if (2 > argc)
{
fprintf(stderr, "Missing arguments. Usage: %s day-of-year year\n", argv[0]);
return EXIT_FAILURE;
}
short unsigned int day_of_year = atoi(argv[1]);
short unsigned int year = atoi(argv[2]);
char date[16] = "";
if (-1 == to_date(date, sizeof(date), "%m/%d/%Y", day_of_year, year))
{
perror("to_date() failed");
return EXIT_FAILURE;
}
printf("Result: day %d of year %d is '%s'.\n", day_of_year, year, date);
return EXIT_SUCCESS;
}
像这样称呼
$ ./main 2 2000
获取
Result: day 2 of year 2000 is '01/02/2000'.
答案 3 :(得分:0)
1901年至2099年,可以使用时间函数轻松完成。
void Makedate(int year, int day, struct tm *dest) {
struct tm tm1 = { 0 };
// Leap year every 4 years, lets do calc referencing 2000-2003
tm1.tm_year = 2000 - 1900 + year % 4;
tm1.tm_mday = day; // Make the Jan 1st to Jan 366th. OK to be out of range.
// Avoid day changes due to DST by using Noon. BTW I doubt this is needed (CYA)
tm1.tm_hour = 12;
// mktime adjusts our fields for us, setting the month, mday, dow, etc.
mktime(&tm1);
tm1.tm_year = year - 1900; // set to selected year
*dest = tm1;
}
int main() {
struct tm tm0;
Makedate(2013, 1, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2013, 365, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2020, 1, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2020, 366, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
return 0;
}
y:2013 m: 1 d: 1
y:2013 m:12 d:31
y:2020 m: 1 d: 1
y:2020 m:12 d:31