Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sin() in a formula in xcode

Currently I am trying to implement this formula pi = n*(sin(180/n)); in xcode. But just writing it like this gives me huge numbers like -12425553 or 23082083. How can I fix it??

I used int n; double pi;.

Update:

I tried using M_PI/180 to convert to degrees but it still doesn't work. Any suggestions??

pi = n*sin((180/n) * (M_PI/180));

By the way I removed the asterisks!!

like image 677
Philipp Braun Avatar asked Aug 10 '26 19:08

Philipp Braun


2 Answers

There are three problems with your code:

  • You define primitives as pointers (you need to remove asterisks)
  • You assume that sin takes degrees (it takes radians)
  • You use integer division (if sin indeed took degrees, which it does not, you should have used 180.0 in place of 180)

To convert degrees to radians, use this formula:

(degrees*M_PI)/180.0
like image 149
Sergey Kalinichenko Avatar answered Aug 12 '26 12:08

Sergey Kalinichenko


Most likely the '180/n' part is dividing integers. Try:

sin(180.0/n);

Edit as @sosborn correctly pointed, you are doing arithmetic among 'pointer to int', not ints themselves.

like image 29
Nicolas Miari Avatar answered Aug 12 '26 14:08

Nicolas Miari