C:无论如何我可以让模运算符处理非整数值吗?

标签 c operator-keyword modulo

<分区>

每当变量值达到或超过 2 PI 时,我都需要将名为 theta 的变量的值重置回 0。我在想一些事情:

int n = 10;
float inc = 2*PI/n;
for(int i=0;i<10;i++)
    theta = (theta + inc) % 2*PI;

当然它不会工作,因为 % 在 C 中对 float 不起作用。是否有另一种等效或更好的方法来实现我在这里尝试做的事情?欢迎所有回复。谢谢

最佳答案

使用标准的fmod 函数。参见 https://en.cppreference.com/w/c/numeric/math/fmod或 C17 标准中的 7.2.10。

The fmod functions return the value x − n y , for some integer n such that, if y is nonzero, the result has the same sign as x and magnitude less than the magnitude of y.

所以 theta = fmod(theta, 2*PI) 应该是你想要的,如果我理解你的问题的话。

如果确实必须在 float 而不是 double 上完成,您可以改用 fmodf

关于C:无论如何我可以让模运算符处理非整数值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62597353/

相关文章:

c - 使用指针和数组调试程序

javascript - 当变量为空时,JavaScript中的三元运算符

c - `if (variable % 2 == 0)`时程序崩溃

c - 警告 : pointer targets in passing argument 1 of '__builtin___strncpy_chk' differ in signedness

c - getfloat 返回 23.7999

c - 在 C 函数中传递泛型参数

python - 发现与 and 运算符混淆

c++ - 如何修复 : binary = :no operator exists which takes a RHS of const & fullName

algorithm - 找到一个一般大小的互质数

c++ - 如何避免在 std::modf 中使用临时变量?