Obj-C Calculator - Radians to Degrees
I've been watching the Stanford CS193P lectures and I've been working on the assignment calculator. I got through the first assignment fairly easily, and I'm trying 开发者_JS百科to do the extra credit for the assignment now. I'm stuck however at one of the extra credit questions:
Implement a user-interface for choosing whether the operand to sin() or cos() is considered radians or degrees. When you call sin(x) in the C library, x is assumed to be in radians (i.e. 0 to 2π goes around the circle once), but users might want to enter 180 and press the sin button and get 0 instead of -0.8012 (which is the sine of 180 radians). You could use a UIButton for this and switch out the titleLabel’s text each time the UIButton is pressed, but a better way would be to see if you can figure out how to use a UISwitch by reading the documentation (if you dare!).
I implemented a UISwitch and hooked it up as an IBOutlet. When I perform an 'operation', I check if the switch is on or off and pass this to my model along with the operation to perform. In my sin and cos cases, I do the following:
else if ([operation isEqual:@"sin"])
{
if (radians) {
operand = sin(operand);
}
else {
operand = sin(operand) * (180 / M_PI);
}
}
// similar for cos
If radians
(which is a BOOL: YES = radians, no = degrees), then I perform the operation as usually; if the user puts the switch to 'degrees', I want to return the value in degrees, as the assignment states: users might want to enter 180 and press the sin button and get 0 instead of -0.8012 (which is the sine of 180 radians).
However, this code doesn't fully work. When I put the switch to degrees and do sin 180
it returns a value of more or less -45
. Something is wrong there; and I'm not really sure what. I have looked up how to do the conversion and I think I'm doing it right, but apparently not.
I realise this is perhaps better suited for math.stackexchange, but since there was some code I wanted to post I put it here. Can someone provide some advice on the best way to implement this? It's been a while since I even worked with cos or sin, radians and degrees.
Thanks!
Did you perhaps mean operand = sin(operand * M_PI / 180);
?
Try this - It works for me:
if ([operation isEqual:@"sin"])
{
operand = (operand * M_PI/180); // first convert the operand from radians to degrees then perform the operation
operand = sin(operand);
}
Hope this helps
Where did you define operand?
Are you sure that operand
is a CGFloat and not a memory address?
How are you formatting your output? If you are using %e it will output in scientific notation...try doing %f
operand = sin(operand * (M_PI/180));
Did you try
sin( operand ) / 180.0 * M_PI
精彩评论