【问题标题】:Adding time with structure construction in C在 C 中增加结构构造的时间
【发布时间】:2015-05-30 15:07:21
【问题描述】:

我刚刚开始 C,我有一个任务要在输入的日期上加上 1 分钟和 30 秒,该日期由年月日小时分钟秒组成。

所以,我使用了结构构造,因为它是要求之一。 但是,在我必须处理许多情况之前,一切看起来都很好。 例如,如果输入的日期是 2014/12/31 23:58:30 或 2014/2/28 23:59:00 ,我必须更改所有内容。最简单的方法是使用 if 语句进行检查,但我认为应该换一种方式,而不是为我想要处理的每个案例编写大量 if 语句。您能否告诉我是否有另一种更清晰的方法。

struct{
 int day;
 int month;
 int year;
 }a;
struct{
 int hours;
 int minutes;
 int seconds;
 }b;

认为这种方式可能会产生更多的 if 语句。另外一个要求是如果月份输入为 3,则添加 0,输出应为 03。无论如何,我似乎无法从“电话号码”if 语句中逃脱。感谢您的回答和花费的时间!

【问题讨论】:

  • 1) 请向我们展示您迄今为止所做的尝试。 2)您可以考虑使用switch 案例,但话又说回来,如果没有看到您的代码,这可能不是一个好建议。
  • 更简洁的方法是使用 incrementMonth(int currentMonth),incrementMinute(int currentMinute) 之类的函数,其中包含多个 ifs。提供您的代码的缩短版本,让我们了解您的代码的结构。
  • 你可以使用<time.h>吗?如果您正在创建的结构是 struct tm,您可以将其转换为 time_t,添加 90 秒,然后从那里转换回结构。
  • "123123 if 语句"???请将其改写成看起来不像手机短信的内容。

标签: c if-statement struct


【解决方案1】:

所以,让我们假设您并不关心所有关于时间的真正困难的部分。例如:leap secondsleap yearsdaylight savings timechanges to daylight savings timetime zone changes

如果你不这样做,那么让我们像构建一个自定义加法运算符一样考虑这个问题。

struct time {
    unsigned year;
    unsigned month;
    unsigned day;
    unsigned hour;
    unsigned minute;
    unsigned second;
};

struct time time_add(struct time date, struct time delta) {
    date.year   += delta.year;
    date.month  += delta.month;
    date.day    += delta.day;
    date.hour   += delta.hour;
    date.minute += delta.minute;
    date.second += delta.second;

    // Implement corrections
    while (date.second >= 60) {
        date.second -= 60;
        date.minute += 1;
    }
    while (date.minute >= 60) {
        date.minute -= 60;
        date.hour += 1;
    }
    while (date.hour >= 24) {
        date.hour -= 24;
        date.day += 1;
    }
    // and so on..

    return date;
}

使用这种方法,您应该能够显着减少您必须处理的案件数量。

【讨论】:

  • 可以将int 溢出和极端日期范围添加到不案例列表中。
【解决方案2】:

如果你想用某种方式来缩写它(或者用一些通用的方式来添加奇怪的、可变的、基于记数的数字,例如旧的便士、先令和英镑系统),试着把这些东西放在一个数组中,然后另一个固定数组中每个数字的编号基数,因此您可以执行以下操作:

int basis[] = {
    100, /* hundreds of a second in a second */
    60,  /* secs in a minute */
    60,  /* mins in an hour */
    12,  /* hours in a cycle(AM/PM) */
    2,   /* cycles in a day */
    30,  /* days, but be careful, not all months have 30 days */
    12,  /* months */
    100, /* years in a century */
    0,   /* centuries, and sentinel to stop. */
};

int carry = 0;
int i;
for (i = 0; i; i++) { /* sum array a and b into c */
    c[i] = a[i] + b[i] + carry; /* sum digit i */
    carry = c[i] / basis[i]; /* determine carry, can be abreviated */
    c[i] %= basis[i]; /* determine final value, can be abreviated */
} /* for */
c[i] = a[i] + b[i] + carry;  /* finally, centuries, not based */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多