January 5th, 2013, 06:19 PM
Help with number conversion
Hi guys. I'm trying to build a program that changes rectangular values (e.g; X + jY) Into a polar form (Length and angle). I've gotten this far with the code:
int a, b, c, d;
float e, f;
printf("Enter first real number number\n");
printf("Enter first imaginary number number\n");
c = pow(b,2)+pow(a,2);
d = sqrt(c);
printf("Total = %d\n",d); /* this is the length in polar form */
e = atan(b/a);
f = e*(180/3.14159);
printf("%f\n",f); /*this is Angle in polar form*/
I'm currently having 2 problems:
1. in instances where a > b , the output angle is always 0
2. my results appear to be the 'wrong way round' so to speak. For example, if a = 1 and b = 40, I attain a value of 88.5 on the program. However, on a calculator, the value is 1.5. These add to make 90, which suggests my results may be out of phase?
I was hoping someone here would have a better idea. I'm not a programmer forefront, and problems like this are really where my knowledge ends.
Thanks very much
January 5th, 2013, 07:43 PM
Use double, not int, for your quantities. Even if you want to restrict your inputs to be integers (why?), you're going to run into trouble. For example, if a and b are ints, then b/a in C is integer division, which results in an int (basically, it's the true quotient truncated to an integer). sqrt(c) will be computed correctly (c will be promoted implicitly to double before the call), but obviously, if the result is not an integer, then assigning its value to the int variable d will not result in the correct value.
Also, atan2(y, x) is better than atan(y/x) here, since atan2 will give you an angle in the correct quadrant.
January 6th, 2013, 07:40 AM
Thanks for the reply. I'm still having a little trouble with the use of doubles. It's the first time i've come across them. Is there any good references, or example you suggest I look at, as google seems to be coming up fruitless.
Originally Posted by Lux Perpetua
The atan2 tip was perfect. Cannot thank you enough for that one.