将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:32:52  来源:igfitidea点击:

Incrementing a variable by 0.025 for each loop in BASH (NOT loop variable)

bash

提问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".

或者,这个问题可能告诉你“RubyPythonPerlAwk写我”。

回答by tsu1980

#!/bin/sh

k=1.00
incl=0.025
k=`echo $k + $incl | bc`

echo $k

回答by mkb

Bash doesn't handle floating point math whatsoever. You need help from an external tool like bc.

Bash 不处理任何浮点数学。您需要像bc这样的外部工具的帮助。