Subtracting two time interval

2019-08-31 08:12发布

I wanted to subtract two time interval. here one time interval is 5hour 30 minute and other is current time.the code is written as follow.

main()
{
int Time1;
int Time2;
int hour=10;
int minute=5;
int second=13;
int h; int m;
int  Ntime;
Time1=(60*5)+(30);
Time2=60*hour+minute;
Ntime=Time2-Time1;
 m=(Ntime%60);
  Ntime=Ntime/60;
  h=(int)(Ntime);
printf("hour after subtraction is : %d hour %d min",h,m) 

}

标签: c time arduino
3条回答
淡お忘
2楼-- · 2019-08-31 08:15

The % operator is meant for integer values only. It won't work with a double variable. Change your code to: Ntime = (((int)Ntime%60) / 100 + (Ntime / 60));

查看更多
Explosion°爆炸
3楼-- · 2019-08-31 08:24

I have not looked at any logical errors in your program but the error you post is due to the fact that the mod operator i.e. % expects the operand to be integer. So if you modify your code in this way, it should remove the error.

main()
{
int Time1;
int Time2;
int hour=10;
int minute=5;
int second=13;
int h; int m;
int  Ntime; //double has been changed to int
double Ntime2;
Time1=(3600*5)+(60*30);
Time2=(3600*hour)+(60*minute)+second;
Ntime=Time2-Time1;
Ntime2=((double)((Ntime%60)/100) + (double)(Ntime/60));

h=(int)(Ntime2);
m=((Ntime2 - (double)h)*100);
printf("hour after subtraction is : %d hour %d min",h,m) 
}

There is too much type casting involved in your code, you should look for a simpler way to do this. Look into the time.h header file, you may find something useful to work with.

查看更多
手持菜刀,她持情操
4楼-- · 2019-08-31 08:38

change your statement of calculating Ntime to,

Ntime=((float)((int)Ntime%60)/100+(Ntime/60));

you need to type cast to float/double otherwise /100 will result in integer so fractional part will be truncated.

查看更多
登录 后发表回答