Sheerpower Logo
Q.3  A Fancy Calculator

A Fancy Calculator

This is a Fancy Calculator. You can use all the math operations that Sheerpower supports with this calculator. The code is provided below, followed by a detailed explanation. Feel free to copy the code and modify it as you like.
// Fancy Calculator in Sheerpower print 'Calculator' print 'Enter any expression (e.g. 2+3) to evaluate.' print 'Type Q to quit' do line input prompt '>> ': expr$ lc_expr$ = lcase$(expr$) if lc_expr$ = 'q' then exit do when exception in print eval(expr$) use print extext$;' for '; expr$ end when loop print 'done' stop

Program Explanation:

1. Introduction:

The program starts by printing a welcome message "Calculator" to the user. It then instructs the user to enter any arithmetic expression (like 2+3) to evaluate it. The user is also informed that they can type Q to quit the program.

2. Input Loop:

The program enters a loop that will continue until the user decides to quit. The line input statement displays a prompt (>>) and waits for the user to enter an expression. The user's input is stored in the string variable expr$.

3. Convert Input to Lowercase:

The program converts the user's input to lowercase using the lcase$() function and stores it in the variable lc_expr$. It checks if the lowercase input is q. If it is, the loop exits, effectively ending the program.

4. Evaluate the Expression:

The program attempts to evaluate the expression entered by the user using the eval() function. This function interprets the string as an arithmetic expression and computes its value. The when exception in ... use block is used to handle any errors that might occur during the evaluation. For example, if the user enters an invalid expression, an exception will be raised.

  • If the evaluation is successful, the result is printed.
  • If an error occurs, the program prints an error message using extext$, which contains the error description, followed by the invalid expression.

5. End of Program:

After the loop ends (when the user types Q), the program prints done to indicate that the calculator has finished. The stop statement is used to terminate the program.

Hide Description

    

       


      

Enter or modify the code below, and then click on RUN

Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use.
Wide screen