如何在Bash中漂浮?(小数点后) [英] How to round float in Bash? (to a decimal)

查看:70
本文介绍了如何在Bash中漂浮?(小数点后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想四舍五入以使这些变量的总和等于1.这是我的程序:

I want to round my float variables in order for the sum of these variables to be equal 1. Here is my program :

for float in 0.0 0.001 0.01 0.025 0.05 0.075 0.1 0.125 0.15 0.175 0.2 0.225 0.25; do
w1=`echo "1.0 - $float" | bc -l`   
w2=`echo "$w1/3" | bc -l`
echo "$w2 0.0 $w2 0.0 0.0 0.0 $w2 $float 0.0 0.0 0.0 0.0"
done

其中 3 * $ w2 + $ float 的总和必须为1.00.我是一个初学者,但我需要用它来计算一些结果.

Where the sum 3*$w2 + $float has to be 1.00. I'm a beginner but I need this to compute some results.

我已经尝试过在互联网上找到的要对 w2 进行四舍五入的方法,但是我没有设法使其起作用.而且它必须四舍五入并且不能被截断,以使最终结果为1.00.

I tried already what I found on the internet to round w2, but I didn't manage to make it work. And it has to be rounded and not truncated for the final result to be 1.00.

推荐答案

bc 可让您使用变量,因此您可以说:

bc lets you use variables, so you can say:

for float in 0.0 0.001 0.01 0.025 0.05 0.075 0.1 0.125 0.15 0.175 0.2 0.225 0.25; do 
    { read w2; read f; } < <(
        bc -l <<< "scale=5; w2=(1.0-$float)/3; w2; 1.0-3*w2"
    )
    echo "$w2 0.0 $w2 0.0 0.0 0.0 $w2 $f 0.0 0.0 0.0 0.0"
done

.33333 0.0 .33333 0.0 0.0 0.0 .33333 .00001 0.0 0.0 0.0 0.0
.33300 0.0 .33300 0.0 0.0 0.0 .33300 .00100 0.0 0.0 0.0 0.0
.33000 0.0 .33000 0.0 0.0 0.0 .33000 .01000 0.0 0.0 0.0 0.0
.32500 0.0 .32500 0.0 0.0 0.0 .32500 .02500 0.0 0.0 0.0 0.0
.31666 0.0 .31666 0.0 0.0 0.0 .31666 .05002 0.0 0.0 0.0 0.0
.30833 0.0 .30833 0.0 0.0 0.0 .30833 .07501 0.0 0.0 0.0 0.0
.30000 0.0 .30000 0.0 0.0 0.0 .30000 .10000 0.0 0.0 0.0 0.0
.29166 0.0 .29166 0.0 0.0 0.0 .29166 .12502 0.0 0.0 0.0 0.0
.28333 0.0 .28333 0.0 0.0 0.0 .28333 .15001 0.0 0.0 0.0 0.0
.27500 0.0 .27500 0.0 0.0 0.0 .27500 .17500 0.0 0.0 0.0 0.0
.26666 0.0 .26666 0.0 0.0 0.0 .26666 .20002 0.0 0.0 0.0 0.0
.25833 0.0 .25833 0.0 0.0 0.0 .25833 .22501 0.0 0.0 0.0 0.0
.25000 0.0 .25000 0.0 0.0 0.0 .25000 .25000 0.0 0.0 0.0 0.0

根据需要调整 scale =?.

这篇关于如何在Bash中漂浮?(小数点后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆