zoukankan      html  css  js  c++  java
  • 使用go实现基于命令行的计算器程序

    项目目录结构

    calcs.go源文件

    package main
    
    import (
    	"fmt"
    	"os"
    	"strconv"
    	"myapp/simplemath"
    )
    
    var Usage = func() {
    	fmt.Println("USAGE: calcs command [arguments] ...")
    	fmt.Println("
    The commands are:
    	add	Addition of two values.
    	sqrt	Square root of a ono-negative value.")
    }
    
    func main()  {
    	args := os.Args//接受命令行参数
    	if args == nil || len(args) < 3 {
    		Usage()
    		return
    	}
    
    	switch args[1] {
    	case "add":
    		if len(args) != 4{
    			fmt.Println("USAGE:calcs add <integer1> <interger2>")
    			return
    		}
    		v1,err1 := strconv.Atoi(args[2])
    		v2,err2 := strconv.Atoi(args[3])
    		if err1 != nil || err2 != nil {
    			fmt.Println("USAGE: calcs add <integer1> <integer2>")
    			return
    		}
    		ret := simplemath.Add(v1,v2)
    		fmt.Println("Result: ",ret)
    	case "sqrt":
    		if len(args) != 3 {
    			fmt.Println("USAGE: calcs sqrt <integer>")
    		}
    		v , err := strconv.Atoi(args[2])
    		if err != nil {
    			fmt.Println("USAGE: calcs sqrt <integer>")
    			return
    		}
    		ret := simplemath.Sqrt(v)
    		fmt.Println("Result: ",ret)
    	default:
    		Usage()
    	}
    }
    

    add.go源文件

    package simplemath
    
    func Add (a int,b int) int {
    	return a + b
    }
    

    add_test.go源文件,测试程序

    package simplemath
    
    import "testing"
    
    func TestAdd(t *testing.T) {
    	r := Add(1,2)
    	if r != 3 {
    		t.Errorf("Add(1,2) failed. Got %d,expected 3.",r)
    	}
    	println(r)
    }
    

    sqrt.go源文件

    package simplemath
    
    import (
    	"math"
    )
    
    func Sqrt(i int) int {
    	v := math.Sqrt(float64(i))
    	return int(v)
    }
    

    sqrt_test.go源文件,测试程序

    package simplemath
    
    import "testing"
    
    func TestSqrt(t *testing.T) {
    	v := Sqrt(16)
    	if v != 4 {
    		t.Errorf("Sqrt(16) failed. Got %v,expected 4.",v)
    	}
    	println(v)
    }
    

    然后编译calcs.go

    测试结果

  • 相关阅读:
    Attention in Super-Resolution[阅读笔记][RCAN][SAN][HAN]
    docker安装oracle11g
    timeSetEvent
    有意思的中文转拼音用来区分26个小类用于缩小列表大小减少循环
    jsp中的out.println爆红
    记一次Jdbc的配置文件无法加载
    Java静态块
    解决Unable to save settings: Failed to save settings. Please restart IntelliJ IDEA报错
    html5,图文混排垂直居中
    Sql server语句执行时间查看
  • 原文地址:https://www.cnblogs.com/yxhblogs/p/8151430.html
Copyright © 2011-2022 走看看