cs193p – Assignment #1 Task #2

cs193p-assignment-1-task-2

Your Calculator already works with floating point numbers (e.g. if you touch 3 ÷ 4 =, it will properly show 0.75), however, there is no way for the user to enter a floating point number directly. Fix this by allowing legal floating point numbers to be entered (e.g. “192.168.0.1” is not a legal floating point number!). You will need to have a “.” button in your calculator. Don’t worry too much about precision or significant digits in this assignment (doing so is Extra Credit).

… the button has already been added during the lecture. Because it has been copied from a digit button it points already to touchDigit. When the user is in the middle of typing, only add the digit if it is not a “.”, or if there is not already one on the display. For new new numbers, add a leading zero if necessary:

    @IBAction func touchDigit(_ sender: UIButton) {
        ...
        if userIsInTheMiddleOfTyping {
            ...
            if "." != digit || !textCurrentlyInDisplay.contains(".") {
                display.text = textCurrentlyInDisplay + digit
            }
        } else {
            display.text = "." == digit ? "0." : digit
            ...
        }        
    }

As requested in the hints we added only a single line, and adjusted another one.

The complete code for the assignment #1 task #2 is available on GitHub.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

One thought on “cs193p – Assignment #1 Task #2”

Leave a Reply

Your email address will not be published.