将 BASH 中的每个循环的变量增加 0.025(非循环变量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5174841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incrementing a variable by 0.025 for each loop in BASH (NOT loop variable)
提问by Amit
I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
我想在循环内增加一个变量 k 。每个增量为 0.025。我尝试使用:
let "k += 0.025"
let "k += 0.025"
and
和
let "$k += 0.025"
let "$k += 0.025"
and
和
k += 0.025
k += 0.025
and many other variations. Does anyone know how to accomplish this?
以及许多其他变体。有谁知道如何做到这一点?
采纳答案by Dave Jarvis
Use integer math and then convert to decimal when needed.
使用整数数学,然后在需要时转换为十进制。
#!/bin/bash
k=25
# Start of loop
#
# Increment variable by 0.025 (times 1000).
#
let k="$k+25"
# Get value as fraction (uses bc).
#
v=$(echo "$k/1000"|bc -l)
# End of loop
#
echo $v
Save as t.sh, then:
另存为t.sh,然后:
$ chmod +x t.sh
$ ./t.sh
.05000000000000000000
回答by DigitalRoss
You may be working on some giant bash masterpiece that can't be rewritten without a king's ransom.
您可能正在制作一些没有国王的赎金就无法重写的巨型 bash 杰作。
Alternatively, this problem may be telling you "write me in Rubyor Pythonor Perlor Awk".
或者,这个问题可能告诉你“用Ruby、Python、Perl或Awk写我”。
回答by tsu1980
#!/bin/sh
k=1.00
incl=0.025
k=`echo $k + $incl | bc`
echo $k

