[英]Floating point calculation in Bash and "line 16: [: missing ']'" how to bring decimal point on output
I wrote this code to get temperature in floating point in bash.我写了这段代码是为了在 bash 中获得浮点温度。 this gives me an error:
这给了我一个错误:
line 16: [: missing ']'
Here is the code:这是代码:
#!/bin/bash
echo "Celsius Fahrenheit"
echo "--------------------------"
counter=0
while [ $counter -le 25 ]:
do
let "val = ($counter * 9/5) + 32"
if [ $counter -le 9 ]
then
whitespace=" "
else
whitespace=" "
fi
echo "$counter$whitespace$val"
((counter++))
if [[ "$REPLY" =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
fi
done
exit 1
Your while
is using colon ( :
) when it should be a semicolon ( ;
):您的
while
使用冒号 ( :
) 而应该是分号 ( ;
):
#!/bin/bash
echo "Celsius Fahrenheit"
echo "--------------------------"
counter=0
while [ $counter -le 25 ];
do
let "val = ($counter * 9/5) + 32"
if [ $counter -le 9 ]
then
whitespace=" "
else
whitespace=" "
fi
echo "$counter$whitespace$val"
((counter++))
if [[ "$REPLY" =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
fi
done
exit 1
Output:输出:
$ /usr/bin/diff old.sh new.sh
5c5
< while [ $counter -le 25 ]:
---
> while [ $counter -le 25 ];
$ sh old.sh
Celsius Fahrenheit
--------------------------
old.sh: line 5: [: missing `]'
$ sh new.sh
Celsius Fahrenheit
--------------------------
0 32
1 33
2 35
3 37
4 39
5 41
6 42
7 44
8 46
9 48
10 50
11 51
12 53
13 55
14 57
15 59
16 60
17 62
18 64
19 66
20 68
21 69
22 71
23 73
24 75
25 77
use bc will give floating point results使用 bc 将给出浮点结果
val= bc <<<"scale=2;($counter*9/5)+32"
val=
bc <<<"scale=2;($counter*9/5)+32"
#!/bin/bash
echo "Celsius Fahrenheit"
echo "--------------------------"
counter=0
while [ $counter -le 25 ];
do
val=`bc <<<"scale=2;($counter*9/5)+32"`
if [ $counter -le 9 ]
then
whitespace=" "
else
whitespace=" "
fi
echo "$counter$whitespace$val"
((counter++))
if [[ "$REPLY" =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
fi
done
exit 1
The answer is答案是
Celsius Fahrenheit
--------------------------
0 32.00
1 33.80
2 35.60
3 37.40
4 39.20
5 41.00
6 42.80
7 44.60
8 46.40
9 48.20
10 50.00
11 51.80
12 53.60
13 55.40
14 57.20
15 59.00
16 60.80
17 62.60
18 64.40
19 66.20
20 68.00
21 69.80
22 71.60
23 73.40
24 75.20
25 77.00
If it helps hit correct answer如果它有助于击中正确答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.