我需要在C ++模

编程入门 行业动态 更新时间:2024-10-26 12:29:01
本文介绍了我需要在C ++模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个实数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 ++模

本文发布于:2023-11-27 08:48:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!