이 질문은 매우 구체적이지만 목표 -C 계산기의 작동 방식을 배우려는 사람들에게 도움이된다고 생각합니다.새 값 대신 마지막 결과로 작동하는 계산기
앱은 다음과 같이 작동합니다. 숫자가 눌러졌습니다. 세 누름 같으면 다른 번호가 눌려
- (IBAction)operandPressed:(id)sender
{
//Calculate from previous operand
[self calculate];
//Get the NEW operand from the button pressed
operand = ((UIButton*)sender).titleLabel.text;
}
피연산자 가압
- (IBAction)numberButtonPressed:(id)sender
{
//Resets label after calculations are shown from previous operations
if (isMainLabelTextTemporary)
{
(mainLabel.text = @"0");
isMainLabelTextTemporary = NO;
}
NSString *numString = ((UIButton*)sender).titleLabel.text;
//Get the string from the button label and main label
mainLabel.text = [mainLabelString stringByAppendingFormat:numString];
}
는 결과로 계산된다;
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
}
- (void)calculate
{
//Get the current value on screen
double currentValue = [mainLabel.text doubleValue];
// If we already have a value stored and the current # is not 0, operate the values
if (lastKnownValue != 0 && currentValue != 0)
{
if ([operand isEqualToString:@"+"])
lastKnownValue += currentValue;
else if ([operand isEqualToString:@"-"])
lastKnownValue -= currentValue;
else if ([operand isEqualToString:@"×"])
lastKnownValue *= currentValue;
else if ([operand isEqualToString:@"/"])
lastKnownValue /= currentValue;
else if ([operand isEqualToString:@"xʸ"])
lastKnownValue = (pow(lastKnownValue, currentValue));
else if ([operand isEqualToString:@"ʸ√x"])
lastKnownValue = (pow(lastKnownValue, 1.0/currentValue));
}
else
lastKnownValue = currentValue;
//Set the new value to the main label
mainLabel.text = [NSString stringWithFormat:@"%F", lastKnownValue];
isMainLabelTextTemporary = YES;
}
명확
- (IBAction)clearPressed:(id)sender
{
lastKnownValue = 0;
mainLabel.text = @"0";
isMainLabelTextTemporary = NO;
operand = @"";
}
연산함으로써되는 계산 방법은 잘 작동하고 그 결과가 올바르게 표시됩니다. clear
을 누르면 다른 문제가 발생하지 않지만 결과가 표시된 후에 다른 번호를 입력하고 계산할 경우 마지막 결과가 대신 수행됩니다. 코드를 여러 번 읽은 후 값을 계속 모니터링하기 위해 NSLogs
을 설정했지만 실수를 찾는 행운이 없었습니다. 무엇이 잘못 되었습니까?
EDIT 용액 : 북두칠성의 대답 암시 된 바와 같이, 용액이 결과 후에 이렇게, lastKnownValue
재설정되고 계산은 0으로 설정하여 표시되어, 새로운 하나가 입력 될 때 코드가 덮어 쓰기한다 :
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
//reset lastKnownValue
lastKnownValue = 0;
}
많은 감사! 최대한 빨리 이해하고, 결과를보고하고보고 할 것입니다! –
위대한! 예, 모든 버튼과 숫자를 단 하나의 수식 문자열로 곧 만들어서 더 간단하게 만들 것입니다. 다시 감사합니다 :) –
'NSExpression'을 살펴보고 도움을 줄 수있는 방법을 찾아보십시오. – Wain