我有一个实数x,我想得到数字(x mod 2 * PI)= y,其中y在0和2 * PI之间。
我可以做一个循环,如果x是负的,我只是继续添加2 * pi,直到我的数字在[0,2 * pi]的范围内,或者如果x大于2 * pi我可以只是保持减去。
我试过这个:
fmod(-0.3434073,2 * M_PI);但这仍然是-0.3434073。
解决方案编辑:填入Notinlist以便更快地回答。 p>
在C99标准中,7.12.10.1节可以这样说:
fmod函数返回值x-ny,对于一些整数n,使得如果y不为零,则结果具有与x相同的符号,并且幅度小于y的幅度。如果y为零,则无论发生域错误还是fmod函数返回零都是实现定义的。
double fmod_positive(double x,double y){ double tmp = fmod(x,y); return x< 0? tmp + y:tmp; }
I have a real number x and I want to get the number (x mod 2*PI) =y, where y is between 0 and 2*PI.
I could do it with a loop and if x is negative I just keep adding 2*pi until my number is in range of [0,2*pi] or if x is greater the 2*pi I could just keep subtracting. However, I hope there is a more elegant way to do this.
I tried this:
fmod(-0.3434073,2*M_PI);but this remains -0.3434073. Why and how can I get it working as I want it to?
解决方案Edit: Credits to Notinlist for answering faster.
In the C99 standard, section 7.12.10.1 has this to say:
The fmod functions return the value x − ny, 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. If y is zero, whether a domain error occurs or the fmod functions return zero is implementation- defined.
Going by this, you need to add y if you want the proper sign.
All in all:
double fmod_positive(double x, double y){ double tmp = fmod(x, y); return x < 0 ? tmp + y : tmp; }
更多推荐
我需要在C ++模
发布评论