【发布时间】:2020-02-02 01:48:34
【问题描述】:
我正在尝试用 C 语言制作秒表来收集钟摆的时间段。虽然这里没有显示,i 是一个距离计数器,传感器测量它与摆锤之间的距离。所以我的目标是在摆锤和传感器之间的距离小于或等于 5 时启动计时器。在这个距离处,摆锤直接位于传感器上方。然后当钟摆回到传感器上时再次启动计时器。
这样做会给我时间。在我的尝试中,我决定使用<time.h> 库并获取摆锤打开和关闭传感器的当前时间,然后进行减法以获得时间段。
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int timeinfo;
int timeinfo1;
int timePeriod;
int main()
{
int i =0;
for (i=0;i<20;i++){
if (i<=5){
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) ); //Collecting the current time when i is less than 5
}
else{
time_t rawtime;
struct tm * timeinfo1;
time ( &rawtime );
timeinfo1 = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo1) );//Collecting the current time when i is greater than 5
}
}
timePeriod = timeinfo1-timeinfo;
printf("%s", timePeriod); // Calculating and printing the time period, the initial minus the final time.
}
代码的结果与我的预期不符,如下所示:
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
Current local time and date: Thu Jan 30 13:00:10 2020
(null)
Process returned 6 (0x6) execution time : 1.604 s
Press any key to continue.
很明显,每次迭代的值没有时间变化,最终的字符串值返回为空。我认为这是因为不可能减去字符串,但我不确定。
【问题讨论】:
-
好的,我改一下
-
答案为 0,因为我的结果显示没有时差
-
我认为
time没有你需要的粒度。 -
好的,你建议我改用什么?