查看“Shell中的浮点数运算”的源代码
←
Shell中的浮点数运算
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
''' with awk: ''' # x=3.1; y=3.2; echo "$x $y" | awk '{if ($1 > $2) print $1; else print $2}' 3.2 echo 3.14 + 5.16 | bc ''' with bc:''' #!/bin/bash echo "Enter value1" read value1 echo "Enter value2" read value2 Result=`echo "$Value1 > $Value2" | bc ` if [ $Result -eq 1 ] then echo "$value1 is greater" fi > echo 3.14 + 5.16 | bc 8.30 Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings. Some shells like zsh understand floating point. Here's a sample comparing bash and zsh. It writes a file t1, then asks bash and zsh to execute it: #!/bin/sh # @(#) s1 Compare bash and zsh for arithmetic. set -o nounset cat >t1 <<'EOF' if [ -n "$BASH_VERSION" ] then echo " From bash, version :$BASH_VERSION:" elif [ -n "$ZSH_VERSION" ] then echo " From zsh, version :$ZSH_VERSION:" else echo " Unknown shell." fi float X Y (( X = 3.0 + 0.5 )) (( Y = 33.0 / 10.0 )) if (( $X < $Y )) # is $X less than $Y ? then echo "\$X=${X}, which is less than \$Y=${Y}" elif (( $X > $Y )) then echo "\$X=${X}, which is greater than \$Y=${Y}" fi EOF echo bash t1 echo zsh t1 exit 0 Producing: % ./s1 From bash, version :2.05b.0(1)-release: t1: line 12: float: command not found t1: line 13: ((: X = 3.0 + 0.5 : syntax error in expression (error token is ".0+ 0.5 ") t1: line 14: ((: Y = 33.0 / 10.0 : syntax error in expression (error token is ".0 / 10.0 ") $X=3, which is less than $Y=33 From zsh, version :4.2.4: $X=3.500000000e+00, which is greater than $Y=3.300000000e+00 '''Here is another example change float to integer''' a=2.25 b=1.35 function f_dec2int() { n=$1 if [ "`echo $n | grep '.'`" != "" ] then echo $n | sed 's/\.//' fi } if [ `f_dec2int $a` -lt `f_dec2int $b` ] then echo true else echo false fi ## `f_dec2int $a` \\ 225 ## `f_dec2int $b` \\ 135
返回至“
Shell中的浮点数运算
”。
导航菜单
个人工具
登录
命名空间
页面
讨论
大陆简体
已展开
已折叠
查看
阅读
查看源代码
查看历史
更多
已展开
已折叠
搜索
导航
首页
社群首页
最近更改
随机页面
帮助
工具
链入页面
相关更改
特殊页面
页面信息