<分区>
每当变量值达到或超过 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 不起作用。是否有另一种等效或更好的方法来实现我在这里尝试做的事情?欢迎所有回复。谢谢
<分区>
每当变量值达到或超过 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/