如何添加两个24小时

时间:2018-03-14 03:58:50

标签: c

您对c中的编码非常陌生,但在我的后续编码问题上非常乐意帮助您。

我想要添加两次(已经是二十四小时时间表示法)。

目前它们都是整数,并且算术加法功能对于整个小时来说都很好(例如800 + 1000),但是因为我们/计算机的数字是十分之一,它不会在60分钟后滚动到下一个小时导致问题另外。

我不确定模数%是否能解决这个问题?理想情况下,我想使用简单的c编码(我理解),而不是开始将计时密钥导入程序。

e.g。

#include <stdio.h>

int main (void)
{

int time1 = 1045; // 10:45am in 24hour time
printf("Time %d ",time1);


int time2 = 930; //9 hours & 30min
    printf("+ time %d", time2);    

int calc = time1 + time2;
printf(" should not equal ... %d\n", calc);

printf("\nInstead they should add to %d\n\n", 2015); //8:15pm in 24hr time

return 0;
}

3 个答案:

答案 0 :(得分:3)

是的,你说模数除法是正确的。请记住,这是余数除法。作为评论更有价值,因为对这类问题提供完整的答案通常是不受欢迎的,但这太长了;这应该让你开始:

#include <stdio.h>

int main(void)
{
  // Assuming the given time has the format hhmm or hmm.
  // This program would be much more useful if these were
  // gathered as command line arguments
  int time1 = 1045;
  int time2 = 930;

  // integer division by 100 gives you the hours based on the
  // assumption that the 1's and 10's place will always be
  // the minutes
  int time1Hours = time1 / 100;  // time1Hours == 10
  int time2Hours = time2 / 100;  // time2Hours == 9

  // modulus division by 100 gives the remainder of integer division,
  // which in this case gives us the minutes
  int time1Min = time1 % 100;  // time1Min == 45
  int time2Min = time2 % 100;  // time2Min == 30

  // now, add them up
  int totalHours = time1Hours + time2Hours;  // totalHours = 19
  int totalMin = time1Min + time2Min;  // totalMin = 75

  // The rest is omitted for you to finish
  // If our total minutes exceed 60 (in this case they do), we
  // need to adjust both the total hours and the total minutes
  // Clearly, there is 1 hour and 15 min in 75 min. How can you
  // pull 1 hour and 15 min from 75 min using integer and modulo
  // (remainder) division, given there are 60 min in an hour?

  // this problem could be taken further by adding days, weeks,
  // years (leap years become more complicated), centuries, etc.

  return 0;
}

答案 1 :(得分:1)

我用了很长时间......

// convert both times hhmm to minutes an sum minutes
// be sure to do integer division 
int time1m = ((time1 / 100) * 60)+(time1 % 100);
int time2m = ((time2 / 100) * 60)+(time2 % 100);
int sumMin = time1m + time2m; 
// convert back to hhmm
int hhmm = ((sumMin / 60) * 100)+(sumMin % 60);

答案 2 :(得分:0)

您还可以包含一天,时间为24小时格式。

#include <stdio.h>
int main()
{
    int t1=2330;
    int t2=2340;
    int sum=((t1/100)*60)+(t1%100)+((t2/100)*60)+(t2%100);
    int day=sum/(24*60);
    sum = sum % (24*60);
    int hours=sum/(60);
    int mins=sum % 60;
    printf("days = %d \t hours = %d \t mins=%d\n",day, hours, mins);
    return 0;
}