Hone logo
Hone
Problems

Go Function Creation: Basic Calculator

This challenge involves creating a simple calculator function in Go. You'll need to implement a function that takes two numbers and an operator as input and returns the result of the operation. This is a fundamental task for understanding function definition and basic arithmetic operations in Go.

Problem Description

Your task is to write a Go function named Calculate that performs basic arithmetic operations. The function should accept three arguments:

  1. num1 (float64): The first operand.
  2. num2 (float64): The second operand.
  3. operator (string): The operator to perform. This can be "+", "-", "*", or "/".

The function should return two values:

  1. result (float64): The outcome of the calculation.
  2. err (error): An error object if the operation is invalid (e.g., division by zero, unknown operator). If the operation is successful, err should be nil.

Key Requirements:

  • Implement the Calculate function in Go.
  • Handle addition, subtraction, multiplication, and division.
  • Return an error for division by zero.
  • Return an error for any operator other than "+", "-", "*", or "/".

Expected Behavior: The function should perform the specified operation and return the correct result. If an error occurs, it should return a meaningful error message.

Edge Cases:

  • Division by zero.
  • Invalid operator input.

Examples

Example 1:

Input: num1 = 10.5, num2 = 5.2, operator = "+"
Output: result = 15.7, err = nil
Explanation: The function successfully adds 10.5 and 5.2.

Example 2:

Input: num1 = 20.0, num2 = 4.0, operator = "/"
Output: result = 5.0, err = nil
Explanation: The function successfully divides 20.0 by 4.0.

Example 3:

Input: num1 = 10.0, num2 = 0.0, operator = "/"
Output: result = 0.0, err = "division by zero is not allowed"
Explanation: Division by zero is an invalid operation, so an error is returned. The result value can be anything in this case, but 0.0 is a common default.

Example 4:

Input: num1 = 7.0, num2 = 3.0, operator = "%"
Output: result = 0.0, err = "unsupported operator: %"
Explanation: The operator "%" is not supported, so an error is returned.

Constraints

  • num1 and num2 will be floating-point numbers (float64).
  • operator will be a string.
  • The function should return an error for invalid operations, not panic.
  • The performance requirements are minimal; focus on correctness.

Notes

  • You will need to import the errors package for creating custom error messages.
  • Consider using a switch statement for handling different operators.
  • Make sure to handle the case where num2 is zero specifically for the division operation.
Loading editor...
go