Menu
CoddyTech

Recap - Simple Calculator

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 8 of 65.

challenge icon

Challenge

Medium

Write the class Calculator in calculator.gd. It keeps a running result in the float property result, which starts at 0.0.

  • add(number), subtract(number), multiply(number) and divide(number) apply the operation to result with number, store the new result and return it
  • When divide() gets 0, it prints Error: Division by zero, leaves result unchanged and returns it
  • clear() sets result back to 0.0 and returns it
  • get_result() returns result

The supplied code reads how many commands follow, then one command per line, such as add 5, divide 0 or clear. After each command it prints the command name and the value the method returned, and at the end the final result. For add 5, multiply 3, subtract 2, divide 0 and divide 2 it prints:

add -> 5.0
multiply -> 15.0
subtract -> 13.0
Error: Division by zero
divide -> 13.0
divide -> 6.5
Final result: 6.5

Your code goes in calculator.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var calc := Calculator.new()
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var value := 0.0
		match parts[0]:
			"add":
				value = calc.add(float(parts[1]))
			"subtract":
				value = calc.subtract(float(parts[1]))
			"multiply":
				value = calc.multiply(float(parts[1]))
			"divide":
				value = calc.divide(float(parts[1]))
			"clear":
				value = calc.clear()
		print("%s -> %s" % [parts[0], value])
	print("Final result: %s" % calc.get_result())

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler