当前位置:首页 » 网页前端 » shell脚本进行加减乘除
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

shell脚本进行加减乘除

发布时间: 2022-05-26 22:48:41

Ⅰ shell编程case语句乘除法问题

* 在case语句是匹配未知全部的,类似c语言的switch case 中的default,肯定是放最后的。要匹配*可以用转义字符\

Ⅱ shell怎么做加减乘除法

set d = 0;if [ $3 -eq $1] then echo $3 d=$(($1-$2))fi echo $d

Ⅲ 编写一个脚本,进行简单的减法运算,要求提示输入变量

修改如下:

#!/bin/bash
if[$#-eq2];then#数字的相等比较用-eq,字符串的相等比较用=
letnum3="$1-$2"#使用shell内部命令let效率更高
else
read-p"Inputanumber:"num1
read-p"Inputanothernumber:"num2
letnum3=num1-num2#有空格的话要加引号letnum3="num1-num2"
fi
echo$num3

Ⅳ 刚学shell脚本写了个小 计算器,加减除都可以,乘法不行,哪儿错了

你的问题在:elif [ $fangfa = " \* " ]; 这句并不能判断到“*“乘号;
正确的结果如下:
#!/bin/bash
echo "first number"
read a
echo "fangfa"
read fangfa
echo "second number"
read b
if [ "$fangfa" = "+" ];then
echo $(($a+$b))
elif [ "$fangfa" = "-" ];then
echo $(($a-$b))
elif [ "$fangfa" = "*" ];then
echo $(($a*$b))
elif [ "$fangfa" = "/" ];then
echo $(($a/$b))
fi
===============================================
脚本优化版本:
#!/bin/bash

read -p "input first number: " num1
read -p "input operator: " operator
read -p "input second number: " num2

if [ "$operator" == "+" ];then
echo " num1 + num2 = $(($num1+$num2))"
elif [ "$operator" == "-" ];then
echo "num1 - num2 = $(($num1-$num2))"
elif [ "$operator" == "*" ];then
echo "num1 * num2 = $(($num1*$num2))"
elif [ "$operator" == "/" ];then
echo "num1 / num2 = $(($num1/$num2))"
fi

Ⅳ 在Linux下,用shell编写一个简单的计算器,要实现加减乘除4个功能就行了

不用写吧,本来有个 bc 命令可用,没有下载就成.
非要写一个,zsh 的function里有一个,名 zcalc,
贴上来给你

#!/usr/bin/zsh -i
#
# Zsh calculator. Understands most ordinary arithmetic expressions.
# Line editing and history are available. A blank line or `q' quits.
#
# Runs as a script or a function. If used as a function, the history
# is remembered for reuse in a later call (and also currently in the
# shell's own history). There are various problems using this as a
# script, so a function is recommended.
#
# The prompt shows a number for the current line. The corresponding
# result can be referred to with $<line-no>, e.g.
# 1> 32 + 10
# 42
# 2> $1 ** 2
# 1764
# The set of remembered numbers is primed with anything given on the
# command line. For example,
# zcalc '2 * 16'
# 1> 32 # printed by function
# 2> $1 + 2 # typed by user
# 34
# 3>
# Here, 32 is stored as $1. This works in the obvious way for any
# number of arguments.
#
# If the mathfunc library is available, probably understands most system
# mathematical functions. The left parenthesis must be adjacent to the
# end of the function name, to distinguish from shell parameters
# (translation: to prevent the maintainers from having to write proper
# lookahead parsing). For example,
# 1> sqrt(2)
# 1.4142135623730951
# is right, but `sqrt (2)' will give you an error.
#
# You can do things with parameters like
# 1> pi = 4.0 * atan(1)
# too. These go into global parameters, so be careful. You can declare
# local variables, however:
# 1> local pi
# but note this can't appear on the same line as a calculation. Don't
# use the variables listed in the `local' and `integer' lines below
# (translation: I can't be bothered to provide a sandbox).
#
# Some constants are already available: (case sensitive as always):
# PI pi, i.e. 3.1415926545897931
# E e, i.e. 2.7182818284590455
#
# You can also change the output base.
# 1> [#16]
# 1>
# Changes the default output to hexadecimal with numbers preceded by `16#'.
# Note the line isn't remembered.
# 2> [##16]
# 2>
# Change the default output base to hexadecimal with no prefix.
# 3> [#]
# Reset the default output base.
#
# This is based on the builtin feature that you can change the output base
# of a given expression. For example,
# 1> [##16] 32 + 20 / 2
# 2A
# 2>
# prints the result of the calculation in hexadecimal.
#
# You can't change the default input base, but the shell allows any small
# integer as a base:
# 1> 2#1111
# 15
# 2> [##13] 13#6 * 13#9
# 42
# and the standard C-like notation with a leading 0x for hexadecimal is
# also understood. However, leading 0 for octal is not understood --- it's
# too confusing in a calculator. Use 8#777 etc.
#
# Options: -#<base> is the same as a line containing just `[#<base>],
# similarly -##<base>; they set the default output base, with and without
# a base discriminator in front, respectively.
#
#
# To do:
# - separate zcalc history from shell history using arrays --- or allow
# zsh to switch internally to and from array-based history.

emulate -L zsh
setopt extendedglob

local line ans base defbase forms match mbegin mend psvar optlist opt arg
local compcontext="-math-"
integer num outdigits outform=1
# We use our own history file with an automatic pop on exit.
history -ap "${ZDOTDIR:-$HOME}/.zcalc_history"

forms=( '%2$g' '%.*g' '%.*f' '%.*E' )

zmodload -i zsh/mathfunc 2>/dev/null

: ${ZCALCPROMPT="%1v> "}

# Supply some constants.
float PI E
(( PI = 4 * atan(1), E = exp(1) ))

# Process command line
while [[ -n $1 && $1 = -(|[#-]*) ]]; do
optlist=${1[2,-1]}
shift
[[ $optlist = (|-) ]] && break
while [[ -n $optlist ]]; do
opt=${optlist[1]}
optlist=${optlist[2,-1]}
case $opt in
('#') # Default base
if [[ -n $optlist ]]; then
arg=$optlist
optlist=
elif [[ -n $1 ]]; then
arg=$1
shift
else
print "-# requires an argument" >&2
return 1
fi
if [[ $arg != (|\#)[[:digit:]]## ]]; then
print - "-# requires a decimal number as an argument" >&2
return 1
fi
defbase="[#${arg}]"
;;
esac
done
done

for (( num = 1; num <= $#; num++ )); do
# Make sure all arguments have been evaluated.
# The `$' before the second argv forces string rather than numeric
# substitution.
(( argv[$num] = $argv[$num] ))
print "$num> $argv[$num]"
done

psvar[1]=$num
while vared -cehp "${(%)ZCALCPROMPT}" line; do
[[ -z $line ]] && break
# special cases
# Set default base if `[#16]' or `[##16]' etc. on its own.
# Unset it if `[#]' or `[##]'.
if [[ $line = (#b)[[:blank:]]#('[#'(\#|)(<->|)']')[[:blank:]]#(*) ]]; then
if [[ -z $match[4] ]]; then
if [[ -z $match[3] ]]; then
defbase=
else
defbase=$match[1]
fi
print -s -- $line
line=
continue
else
base=$match[1]
fi
else
base=$defbase
fi

print -s -- $line

case ${${line##[[:blank:]]#}%%[[:blank:]]#} in
q) # Exit if `q' on its own.
return 0
;;
norm) # restore output format to default
outform=1
;;
sci[[:blank:]]#(#b)(<->)(#B))
outdigits=$match[1]
outform=2
;;
fix[[:blank:]]#(#b)(<->)(#B))
outdigits=$match[1]
outform=3
;;
eng[[:blank:]]#(#b)(<->)(#B))
outdigits=$match[1]
outform=4
;;
local([[:blank:]]##*|))
eval $line
line=
continue
;;
*)
# Latest value is stored as a string, because it might be floating
# point or integer --- we don't know till after the evaluation, and
# arrays always store scalars anyway.
#
# Since it's a string, we'd better make sure we know which
# base it's in, so don't change that until we actually print it.
eval "ans=\$(( $line ))"
# on error $ans is not set; let user re-edit line
[[ -n $ans ]] || continue
argv[num++]=$ans
psvar[1]=$num
;;
esac
if [[ -n $base ]]; then
print -- $(( $base $ans ))
elif [[ $ans = *.* ]] || (( outdigits )); then
printf "$forms[outform]\n" $outdigits $ans
else
printf "%d\n" $ans
fi
line=
done

return 0

支援小数点,+ - * / , ok

Ⅵ shell编程中两个非整数变量如何做加减乘除运算

假设有两个参数,$1和$2
max=0
if
[
"$1"
-ge
"$2"
]
then
max="$1"
else
max="$2"
fi
比较操作:
-ge
大于等于
-gt
大于
-eq
相等
-lt
小于
-ne
不相等
如果循环比较的话,
试试这样:
max=0
for
args
in
$*
do
if
[
"$max"
-lt
"$args"
]
then
max="$args"
fi
done
这里假设数字都是通过参数传递过来,
用max逐个跟参数比较,得出最大的.

Ⅶ shell 脚本里面从一个文本里面读出一个数字,如何转换成整数我需要用这个数字进行加减乘除

可以参考下面几种方法:

法一:

echo ${var%.*} #这个是直接去除小数点及后面所有内容,只用于bash

法二:

echo $var | awk -F. '{print $1}' #以小数点为分隔符取第一个字段

法三:

echo $var | awk '{print int($0)}' #awk中可直接使用C函数取整

(7)shell脚本进行加减乘除扩展阅读:

shell脚本

shell script是利用shell的功能所写的一个程序,这个程序是使用纯文本文件,将一些shell的语法与指令写在里面,然后用正规表示法,管道命令以及数据流重导向等功能,以达到我们所想要的处理目的。

更明白地来说,shell script就像早期dos年代的.bat,最简单的功能就是将许多指令汇整写一起,让使用者很容易地就能够一个操作执行多个命令。

Ⅷ 1.linux系统下shell脚本用case语句编写四则运算 2.linux系统下shell脚本输入数字串。进行反序输出

原来我拿shell写的计算器:
[root@liuxiting testdir]# cat calculator.sh
#!/bin/bash
echo "usage: 1+3 <Enter> ,q <Enter> is quit"
while [ 1 ]
do
read -p "->>" str 1>>/dev/null
a=`echo $str |awk -F '+|-|*|/' '{print $1}'`
if [ $a == q ]
then
break
fi
b=`echo $str |awk -F '+|-|*|/' '{print $2}'`
o=`echo $str |grep -o "[[:punct:]]" | grep -v "\."`
case $o in
+) awk 'BEGIN{printf " =%.2f\n",'$a'+'$b'}';;
-) awk 'BEGIN{printf " =%.2f\n",'$a'-'$b'}';;
\*) awk 'BEGIN{printf " =%.2f\n",'$a'*'$b'}';;
/)if [ $b -eq 0 ]
then
echo 0 Can NOT be denominator!
continue
fi
awk 'BEGIN{printf " =%.2f\n",'$a'/'$b'}';;
#^) awk 'BEGIN{printf " =%.2f\n",'$a'**'$b'}';;
*) echo error;;
esac
done

刚刚写的倒序输出:
[root@liuxiting testdir]# cat XuShuChu.sh
#!/bin/bash
echo "usage: 123456 <Enter>, q <Enter> is quit"
while [ 1 ]
do
echo -n "Pleasw enter number : "
read n
if [ $n == 'q' ]
then
break
fi
sd=0
rev=""
on=$n
echo "$n"
while [ $n -gt 0 ]
do
sd=$(( $n % 10 )) # get Remainder
n=$(( $n / 10 )) # get next digit
rev=$( echo $rev$sd)
done
echo "$on in a reverse order $rev"
done

Ⅸ 怎样用shell语言实现小数的加减乘除运算

原来我拿shell写的计算器:[root@liuxitingtestdir]#catcalculator.sh#!/bin/bashecho"usage:1+3,qisquit"while[1]doread-p"->>"str1>>/dev/nulla=`echo$str|awk-F'+|-|*|/''{print$1}'`if[$a==q]thenbreakfib=`echo$str|awk-F'+|-|*|/''{print$2}'`o=`echo$str|grep-o"[[:punct:]]"|grep-v"\."`case$oin+)awk'BEGIN{printf"=%.2f\n",'$a'+'$b'}';;-)awk'BEGIN{printf"=%.2f\n",'$a'-'$b'}';;\*)awk'BEGIN{printf"=%.2f\n",'$a'*'$b'}';;/)if[$b-eq0]thenecho0CanNOTbedenominator!continuefiawk'BEGIN{printf"=%.2f\n",'$a'/'$b'}';;#^)awk'BEGIN{printf"=%.2f\n",'$a'**'$b'}';;*)echoerror;;esacdone刚刚写的倒序输出:[root@liuxitingtestdir]#catXuShuChu.sh#!/bin/bashecho"usage:123456,qisquit"while[1]doecho-n"Pleaswenternumber:"readnif[$n=='q']thenbreakfisd=0rev=""on=$necho"$n"while[$n-gt0]dosd=$(($n%10))#getRemaindern=$(($n/10))#getnextdigitrev=$(echo$rev$sd)doneecho"$oninareverseorder$rev"done

Ⅹ 用shell做个加减乘除运算

看到真有点疑惑,不是做加法怎么去做减法了。其次set是设置shell变量吧。
还有前两个参数不是数字,最后一个是运算符么?怎么还去测试第三个参数和第一个参数相等。

以下是根据你例子修改的(没检查位置参数不全,不正确这类异常情况。)

#!/bin/bash

exportd=0
if["$3"-eq"+"]
then
echo$3
d=$(($1+$2))
fi
echo$d