使用bash的算术函数援助 [英] Assistance with bash arithmetic function

查看:117
本文介绍了使用bash的算术函数援助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty流利使用Java,但我有一个困难的过渡到庆典

I'm pretty fluent with Java but I'm having a difficult transition into bash

完成名为 ARITH 下面的函数来完成以下任务:

Complete the function named arith below to accomplish the following tasks:


  • 如果变量a的值小于变量的值b然后调用函数添加,

  • if the value of the variable a is less than the value of the variable b then call the function add,

否则调用该函数子。

因此​​,code到目前为止是:

So, the code so far is:

echo "Enter two integers on separate lines"
read a
read b

add()
{
  echo "$a + $b = $((a + b))"
}

sub()
{
  echo "$a - $b = $((a - b))"
}

arith()
{
  If{... # To be completed
}

我认为它应该在的格式

I think it's supposed to be in the format of

arith()
{
    //if(a<b, call function add)
    //else(call function sub)

但我不知道该怎么写。

but I'm not sure how to write that.

推荐答案

除了其功能应该不会被访问全局变量,你可能会写两种:

Except that functions should probably not be accessing global variables, you might write either:

arith()
{
    if [ "$a" -lt "$b" ]
    then add
    else sub
    fi
}

或者

arith()
{
    if [[ "$a" < "$b" ]]
    then add
    else sub
    fi
}

通常情况下,你会写code更像是:

Normally, you'd write code more like:

add()
{
    echo "$1 + $2 = $(($1 + $2))"
}

sub()
{
    echo "$1 - $2 = $(($1 - $2))"
}

arith()
{
    if [[ "$1" < "$2" ]]
    then add "$1" "$2"
    else sub "$1" "$2"
    fi
}

因此​​:

$ arith 1 2
1 + 2 = 3
$ arith 2 1
2 - 1 = 1
$ arith 1 1
1 - 1 = 0
$

这篇关于使用bash的算术函数援助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆