gpt4 book ai didi

bash 和 bc 带小数点的数学计算

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

我正在尝试使用“bc”在 Bash 脚本中实现以下计算,但“scale”选项产生的结果不正确,末尾有 2 个额外的零,这意味着我必须手动修剪它(丑陋).

计算:

((2592000-239)÷2592000)×100

预期结果:99,990779321(但我只想显示小数点后两位)

在 Bash 中:

echo "scale=2; ((2592000-239)/2592000)*100" | bc

99.00

echo "scale=3; ((2592000-239)/2592000)*100" | bc

99.900

echo "scale=4; ((2592000-239)/2592000)*100" | bc

99.9900

echo "scale=5; ((2592000-239)/2592000)*100" | bc

99.99000

echo "scale=8; ((2592000-239)/2592000)*100" | bc

echo "scale=8; ((2592000-239)/2592000)*100" | bc

99.99077900

echo "scale=10; ((2592000-239)/2592000)*100" | bc

99.9907793200

根据手册页:

NUMBERS The most basic element in bc is the number. Numbers are arbitrary precision numbers. This precision is both in the integer part and the fractional part. All numbers are represented internally in decimal and all computation is done in decimal. (This version truncates results from divide and multiply operations.) There are two attributes of numbers, the length and the scale. The length is the total number of significant decimal digits in a number and the scale is the total number of decimal digits after the decimal point. For example: .000001 has a length of 6 and scale of 6. 1935.000 has a length of 7 and a scale of 3.

我理解正确吗?

最佳答案

您可以使用:

echo 'scale=2; 100*(2592000-239)/2592000' | bc -l

99.99

你得到 99.00 因为你首先除法得到 .99 并且当它与 100 相乘时它变成 99.00(由于 scale-2)

关于bash 和 bc 带小数点的数学计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42956147/

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