我想做一个 while 循环,它会说“Hello World”2 秒 500 毫秒(2.5 秒)。我编写的代码当前适用于普通整数,但如果我将其更改为使用 float ,它将停止工作
有什么想法吗?
损坏的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
float timeout = time(NULL) + 2.5;
while(time(NULL) < timeout) {
printf("Hello World\n");
}
return 0;
}
最佳答案
您的代码的问题是:
您使用
float
来表示time()
的结果,这是一个大整数,可能会导致转换不准确,因为浮点值的性质。time()
函数的精度仅精确到秒,因此您的代码永远不会运行 2.5 秒,但始终会运行 3 秒,因为您可以仅以 1 秒的步长进行。
要解决此问题,无需使用浮点值(这没有意义,因为大多数处理时间的函数都使用整数值),您可以使用 gettimeofday()
Linux 上的函数,或 GetSystemTime()
如果您使用的是 Windows,则可以使用该函数。
Linux:
#include <stdio.h>
#include <sys/time.h>
unsigned long long get_time(void) {
struct timeval time;
gettimeofday(&time, NULL);
return time.tv_sec * 1000 * 1000 + time.tv_usec;
}
int main(int argc, char* argv[]) {
unsigned long long timeout = get_time() + 2500000;
// Accurate to the microsecond.
// 2.5 s == 2 500 000 us
while(get_time() < timeout) {
printf("Hello World\n");
}
return 0;
}
Windows:
#include <stdio.h>
#include <windows.h>
unsigned long long get_time(void) {
SYSTEMTIME time;
GetSystemTime(&time);
return time.wSecond * 1000 + time.wMilliseconds;
}
int main(int argc, char* argv[]) {
unsigned long long timeout = get_time() + 2500;
// Accurate to the millisecond.
// 2.5 s == 2 500 ms
while(get_time() < timeout) {
printf("Hello World\n");
}
return 0;
}
注意,在 Windows 上,精度低至毫秒,而在 Linux 上,精度低至微秒。
关于c - 如何使用 float 来设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199740/