gpt4 book ai didi

python - 使用 python bash float 数学

转载 作者:行者123 更新时间:2023-12-01 01:12:56 24 4
gpt4 key购买 nike

我在 bash 中使用 python -c 来做一些 float 数学测试。看来我遗漏了一些东西,因为它给了我一个语法错误。

#!/bin/bash
num1=1.2
num2=3.4
num3=1.5
num4=1.5
volfree=10
TAdd=$(python -c "print $num1 + $num2 + $num3 + $num4")

if (( $(( num1 + num2 + num3 + num4 )) == 0 )) ; then
echo "Sum is equal to 0"
elif (( $(python -c "print $TAdd > $volfree") )); then
echo "(( $( python -c "print $TAdd - $volfree"))) is your final number";
else
echo "something needs to be done"
fi

错误输出:

[user@linuxmachine ~]# bash -x testsize.sh
+ num1=1.2
+ num2=3.4
+ num3=1.5
+ num4=1.5
+ volfree=10
++ python -c 'print 1.2 + 3.4 + 1.5 + 1.5'
+ TAdd=7.6
testsize.sh: line 9: 1.2: syntax error: invalid arithmetic operator (error token is ".2")
[user@linuxmachine ~]#

我的Python版本是Python 2.7.5

最佳答案

我将重写如下:

num1=1.2
num2=3.4
num3=1.5
num4=1.5
volfree=10

# Avoid dynamic code generation; pass values as command-line arguments.
# Compute the diff between the sum and volfree now, rather than waiting to compare them
diff=$(python -c 'from sys import argv; print sum(map(float, argv[1:5])) - argv[5]' "$num1" "$num2" "$num3" "$num4" "$volfree")

# We already know bash doesn't do floating-point arithmetic; don't bother
# checking if num1 + ... + num4 == 0 in shell.
# not (...) maps 0/False to an exit status of 1, and 1/True to 0
if python -c 'import sys; sys.exit(not (float(sys.argv[1] > 0)))' "$diff"; then
echo "$diff is your final number"
else
echo "something needs to be done"
fi

也就是说,这样的俏皮话确实不是 Python 的强项。请改用 awk

diff=$(echo "$num1 $num2 $num3 $num4 $volfree" | awk '{print $1 + $2 + $3 + $4 - $5}')
if echo "$diff" | awk '{exit(!($1 > 0))}'; then
...

关于python - 使用 python bash float 数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com