Last active
July 6, 2017 14:39
-
-
Save x1unix/91b8c86db5613a81db42d96091028b4e to your computer and use it in GitHub Desktop.
Simple Calculator with Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
const ( | |
O_NOTHING float32 = iota | |
O_ADD float32 = iota | |
O_SUBSTRACT float32 = iota | |
O_MULTIPLY float32 = iota | |
O_DIVIDE float32 = iota | |
) | |
const CONFIRM_MSG = "Continue calculation with existing data"; | |
func main() { | |
var initial_value float32 = 0; | |
calc(&initial_value, false); | |
} | |
func calc(previous *float32, continue_calc bool) { | |
var result, operation_ptr = calc_start(previous, continue_calc); | |
if (*operation_ptr == O_NOTHING) { | |
fmt.Println("Nothing selected, aborting..."); | |
return; | |
} | |
fmt.Printf("Result: %f\n", result); | |
var confirm bool = confirm(CONFIRM_MSG); | |
if (confirm) { | |
*previous = result; | |
calc(previous, true) | |
} | |
} | |
func calc_request_operation() float32 { | |
fmt.Println("AVAILABLE OPERATIONS: \n 1: Addition (+)\n 2: Substraction (-)\n 3: Multiply (*)\n 4: Divide (*)\n\n"); | |
fmt.Print("Select operation [0-3]: "); | |
var a float32; | |
fmt.Scanf("%f", &a); | |
return a; | |
} | |
func confirm(text string) bool { | |
fmt.Printf("%s [y/n]?: ", text); | |
var confirm string; | |
fmt.Scanf("%s", &confirm); | |
return (confirm == "y"); | |
} | |
func calc_prompt(num int) float32 { | |
fmt.Print("Enter a number ", num, ": "); | |
var a float32; | |
fmt.Scanf("%f", &a); | |
return a; | |
} | |
func calc_start(start_value *float32, continue_calc bool) (float32, *float32) { | |
var x float32; | |
if (continue_calc) { | |
x = *start_value; | |
} else { | |
x = calc_prompt(1); | |
} | |
var y float32 = calc_prompt(2); | |
var operation float32 = calc_request_operation(); | |
var result float32; | |
switch operation { | |
case O_ADD: | |
result = x + y; | |
break; | |
case O_SUBSTRACT: | |
result = x - y; | |
break; | |
case O_MULTIPLY: | |
result = x * y; | |
break; | |
case O_DIVIDE: | |
result = x / y; | |
break; | |
default: | |
fmt.Println("** ERROR **: Unknown operation: ", operation); | |
operation = O_NOTHING; | |
result = 0; | |
} | |
return result, &operation; | |
} | |
func obj_exp() { | |
var x human = human{"Ivan", 32} | |
var y human = human{"Iva" + "n", 31 + 1} | |
fmt.Println("Object equals? - ", x == y) | |
fmt.Println("Addresses equals? - ", &x == &y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment