더북(TheBook)

두 번째 피연산자의 값 다음에 오는 첫 번째 문자의 위치는 i에 저장된다. iindex에서 상대 위치이므로 indexi를 더해서 피연산자 다음에 오는 다음 연산자를 가리킨다(exp에서 두 번째 피연산자가 마지막 문자열이었다면 문자열의 끝에서 하나 더 뒤를 가리키는 값이 된다).

index 값이 exp의 마지막 문자에서 하나 더 뒤를 가리키면 operators 컨테이너에 남아 있는 연산자들을 모두 실행한다. index가 문자열의 끝에 아직 도달하지 못했고 operators 컨테이너가 비어 있지 않다면 exp에 있는 다음 연산자와 operators 스택 상위에 있는 연산자의 우선순위를 비교한다. 스택 상위에 있는 연산자가 다음 연산자의 우선순위와 같거나 높다면 스택에 있는 연산자를 먼저 실행해야 한다. 그렇지 않은 경우에는 현재 스택 상위에 있는 연산자를 실행하지 않고 문자열에 있는 다음 연산자를 다음 루프를 돌 때 루프 시작 부분에서 스택에 넣는다. 이런 식으로 계속 처리하면서 식을 연산자 우선순위에 따라 적절하게 평가한다.

다음은 예제를 실행한 출력 결과다.

An arithmetic expression can include the operators +, -, *, /, and ^ for exponentiation.

Enter an arithmetic expression and press Enter - enter an empty line to end:

2^0.5

result = 1.41421

Enter an arithmetic expression and press Enter - enter an empty line to end:

2.5e2 + 1.5e1*4 - 1000

result = -690

Enter an arithmetic expression and press Enter - enter an empty line to end:

3*4*5 + 4*5*6 + 5*6*7

result = 390

Enter an arithmetic expression and press Enter - enter an empty line to end:

1/2 + 1/3 +1/4

result = 1.08333

Enter an arithmetic expression and press Enter - enter an empty line to end:

 

Calculator ending...

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.