gpt4 book ai didi

c - 在 C 中将时间间隔除以整数

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:54 27 4
gpt4 key购买 nike

我正在尝试将 timeval 除以一个整数。到目前为止,这是我得到的:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
struct timeval my_time;
struct timeval my_time_quotient;
int i;

gettimeofday(&my_time, NULL);
i = 5;

my_time_quotient = my_time / i;

printf("%d secs, %d msecs\n", (int)my_time_quotient.tv_sec, (int)my_time_quotient.tv_usec);

return 0;
}

当我编译时我得到:

jen@ubuntu:~/$ gcc -g -otimespike timespike.c
timespike.c: In function ‘main’:
timespike.c:15: error: invalid operands to binary / (have ‘struct timeval’ and ‘int’)

求商的正确方法是什么?

最佳答案

您不能直接将 struct 划分为数字类型,即使 struct 表示某种数字也是如此。

您必须首先将您的结构转换为表示微秒数的整数类型。因为元素是 int 类型,所以您需要找到一个位数几乎是 int 两倍的数字类型。希望您的编译器支持 long long int__int64,它们都是 64 位的。

将结构的内容转换为数值类型后,除法将像任何除法一样直接进行。

执行除法后,您需要将结果存储回 timeval,可能会使用“除法后的余数”或“模数”运算符,x % y

关于c - 在 C 中将时间间隔除以整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1712510/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com