Subtracting two time interval

半世苍凉 提交于 2019-12-12 06:38:35

问题


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) 

}

回答1:


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.




回答2:


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));




回答3:


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.



来源:https://stackoverflow.com/questions/22342874/subtracting-two-time-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!