设计一个结构来存储时间和日期.写一个函数来计算两个时间之间的差(以分钟为单位)

Design a structure to store time and date. Write a function to find the difference between two times in minutes

本文关键字:时间 一个 之间 两个 分钟 为单位 存储 结构 日期 函数 计算      更新时间:2023-10-16

我正在自己完成一本O'Reilly的教科书,我现在正在学习结构。其中一个编程练习是:

设计一个结构来存储时间和日期。写一个函数求两个时间的差(以分钟为单位)

我相信我已经把结构部分写下来了,但我对差异函数感到困惑。我太懒了,没有考虑到分开的天数,但是这个问题要求分开的时间,所以我要假装他们说的只是24小时。我可以在函数的参数中调用结构吗?我当然尽力了。任何建议都会有所帮助。由于

我的代码到目前为止(没有完成):

#include <iostream>

int difference(struct date_time);

int main()
{
    return 0;
}

struct date_time{
    int day;
    char month[20];
    int year;
    int second;
    int minute;
    int hour;
} super_date_time = {
    29,
    "may",
    2013,
    30,
    30,
    23
    };
int difference(date_time)
{
    int second1 = 45;
    int minute1 = 50;
    int hour1 = 24;
    std::cout << "Time difference is " << hour1 - int hour
    return 0;
}

坚持你的数据结构…

// Passing your structures by reference (&)
double MA_TimeDiffMinutes(const struct date_time& t1, const struct date_time& t2) {
  // As per your instruction, ignore year, month, day
  int diff = ((t1.hour - t2.hour)*60 + t1.minute - t2.minute)*60 + t1.second - t2.second;
  return diff/60.0;
}
int main() {
  struct date_time t_first;
  struct date_time t_next;
  // TBD fill the fields of t_first and t_next.
  cout << MA_TimeDiffMinutes(t_next, t_first) << endl;
}

考虑使用整数形式的月份而不是字符串。

是,你可以把结构作为参数传递给函数。

process(struct date_time T1) or
process(struct date_time *T1) (struct pointer)

可以通过使用像

这样的函数来计算差值
difference(struct date_time *T1, struct date_time *T2) {  //T2 is recent time
  //process...
  std::cout<<"differ: "<<T2->hour-T1->hour<<"h "<<T2->minute-T1->minute<<"m "<<T2->seconds-T1->seconds<<"s "<<endl;
}

相关文章: