5

Problem: I have IF statement if (x == 180 || x == 360 || x == 540 and so on

How can I keep that list going without writing 180 + 180 * n all out?

Extra info: i want to print "doesnt exist" if sin(x * M_PI / 180) is 0. It is 0 when sin(180), sin(360) and so on.

EDIT: i've tried sin(x2 * M_PI / 180) == 0 but it doesnt work (probably because its close to 0 but not 0)

Karl
  • 89
  • 5

6 Answers6

9

use modulo operand : %

if (x>0 && x%180==0) {..}
P.Bra
  • 264
  • 1
  • 12
6

Look into the mod % operator. It gives you the remainder when doing a divisions. So

(x % 180)   

will be 0 for any integer multiple of 180 (assuming you're not so high that you get some odd wrap-around, say over 4 billion for an unsigned number.)

So you could use.

if ((x % 180) == 0)
Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
3
if (180 <= x && x % 180 == 0)

should do it. Why are you using M_PI ?

Tom's
  • 2,448
  • 10
  • 22
  • If he wants to do it the complicated way with sin, that's what must be done to convert to radians. – kalj Oct 03 '16 at 12:52
2

If x is an integer, you can use remainder operator in your IF statement:

if((x%180) == 0)
{
    // ...
}

Or, if x is not an integer, you can use fmod:

if(fabs(fmod(x, 180.0)) < DBL_EPSILON)
{
    // ...
}
rocambille
  • 15,398
  • 12
  • 50
  • 68
1

A sloppy but practical test is

if ( fabs(sin(a)) < FLT_EPSILON ) 
   treataszero();
Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
  • 2
    When comparing against zero, [epsilon method might not be what you want](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). – user694733 Oct 03 '16 at 13:01
  • No, it's sloppy. But usually dividing by a very small value is almost as bad as a division by zero, because the floating point unit can't cope and accuracy is lost. Generally using FLT_EPSILON as "effectively zero" is good enough, but not for serious numerical work. – Malcolm McLean Oct 03 '16 at 13:06
1

What appears to be OP's higher level problem "tried sin(x2 * M_PI / 180) == 0 but it doesnt work (probably because its close to 0 but not 0)" is the goal is to take the sine of x as expressed in degrees.

Rather than x%180, which is a problem if x is floating point, the idea is to reduces the sin/cos argument to a range of 90 degrees first before converting to radians. No need to give up some precision with an EPSILON comparison.

See c++ Sin and Cos to get the exact value for many cases n*90 degrees and other improved accuracies.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256