How can I compare a number with other numbers without writing them all in C?

Problem: I have an IF if (x == 180 || x == 360 || x == 540 , etc.

How can I save this list without writing 180 + 180 * n all out?

Additional information: I want to print "does not exist" if sin (x * M_PI / 180) is 0. This value is 0 when sin (180), sin (360), etc.

EDIT: I tried sin(x2 * M_PI / 180) == 0 , but it does not work (perhaps because it is close to 0, but not 0)

+5
source share
6 answers

use modulo operand:%

 if (x>0 && x%180==0) {..} 
+9
source

Refer to the mod % operator. This gives you the rest when doing divisions. So

 (x % 180) 

will be 0 for any integer that is a multiple of 180 (unless you are so tall as to get an odd wrap, say, more than 4 billion for an unsigned number).

So you can use.

 if ((x % 180) == 0) 
+6
source
 if (180 <= x && x % 180 == 0) 

must do it. Why are you using M_PI?

+3
source

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

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

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

 if(fabs(fmod(x, 180.0)) < DBL_EPSILON) { // ... } 
+2
source

Careless but practical test

 if ( fabs(sin(a)) < FLT_EPSILON ) treataszero(); 
+1
source

It seems that the problem with the higher OP level is "try sin (x2 * M_PI / 180) == 0, but it does not work (probably because it is close to 0, but not 0)" - this is the goal to take the sine of x as expressed in degrees.

Instead of x%180 , which is a problem if x is a floating point, the idea is to first reduce the sin/cos argument to a range of 90 degrees before converting to radians. No need to give up some accuracy when comparing EPSILON.

See C ++ Sin and Cos for the exact value for many cases of n*90 degrees and other improved accuracy.

+1
source

Source: https://habr.com/ru/post/1257643/


All Articles