最近,我开始在斯坦福大学( U. )开设在线课程“iTunes开发”。
我正试着为前几堂课做家庭作业。我按照演练完成了构建一个基本计算器的过程,但现在我正在尝试第一个任务,但我似乎无法解决它。有一些问题:
努力实施这些措施:
Add the following 4 operation buttons:
• sin : calculates the sine of the top operand on the stack.
• cos : calculates the cosine of the top operand on the stack.
• sqrt : calculates the square root of the top operand on the stack.
• π: calculates (well, conjures up) the value of π. Examples: 3 π * should put
three times the value of π into the display on your calculator, so should 3 Enter π *,
so should π 3 *. Perhaps unexpectedly, π Enter 3 * + would result in 4 times π being
shown. You should understand why this is the case. NOTE: This required task is to add π as
an operation (an operation which takes no arguments off of the operand stack), not a new
way of entering an operand into the display.我的performOperation代码是:
-(double)performOperation:(NSString *)operation
{
double result = 0;
double result1 = 0;
if ([operation isEqualToString:@"+"]){
result = [self popOperand] + [self popOperand];
}else if ([@"*" isEqualToString:operation]){
result = [self popOperand] * [self popOperand];
}
else if ([@"/" isEqualToString:operation]){
result = [self popOperand] / [self popOperand];
}
else if ([@"-" isEqualToString:operation]){
result = [self popOperand] - [self popOperand];
}
else if ([@"C" isEqualToString:operation])
{
[self.operandStack removeAllObjects];
result = 0;
}
else if ([@"sin" isEqualToString:operation])
{
result1 = [self popOperand];
result = sin(result1);
}
else if ([@"cos" isEqualToString:operation])
{
result1 = [self popOperand];
result = cos(result1);
}
else if ([@"sqrt" isEqualToString:operation])
{
result1 = [self popOperand];
result = sqrt(result1);
}
[self pushOperand:result];
return result;
}面对一些问题,例如:
发布于 2012-02-04 08:27:12
你的部门有一个错误。
如果您现在输入'2输入4 enter /',您将得到2 (4/2)作为回答。应该是0.5 (2/4)。
也许这个暗示有帮助。
例如,您可以将您的函数缩短为'result = sin(self popOperand);‘。
无论如何,当您陷入困境时,尝试使用NSLog()并在控制台中打印有趣的值。在调试时非常有用。
发布于 2012-02-05 05:36:22
由于我还在iTunesU中学习这门课,也许这会有所帮助。
首先,阿诺德说的是真的。
你弹出的第一个操作数实际上应该在分母中,所以你必须先把它保存到一边。(另外,由于它是分母,所以您应该确保它不是=0。)你也应该看看你的减法,以确保操作的顺序是正确的。
从5进入3/就是告诉我你错过了一件事。在operationPressed中:在您的CalculatorViewController中,如果我们正在输入一个数字,您是否正在发送enterPressed?
- (IBAction)operationPressed:(UIButton *)sender {
if (self.userIsInTheMiddleOfEnteringANumber) {
[self enterPressed];
}
double result = [self.brain performOperation:sender.currentTitle];
NSString *resultString = [NSString stringWithFormat:@"%g",result];
self.display.text = resultString;
self.history.text = [CalculatorBrain descriptionOfProgram:self.brain.program];
}发布于 2012-02-04 05:27:16
我想你现在缺少的是这一点:
“此要求的任务是将π添加为操作”
考虑以下情况-- 3π*应该生成9.42作为答案。根据您的performOperation:,当遇到'*‘时,操作数堆栈应该为
所需的任务是将π添加为操作。因此,π操作需要做的是将适当的值推到堆栈上,仅此而已。至于其他功能,试一试,并与科学计算器检查,看看你是否正确地实现了它。
https://stackoverflow.com/questions/9138395
复制相似问题