如何将整数和浮点数相加以保持计数?

如何将整数和浮点数相加以保持计数?

我只是想做一些简单的数学运算,但结果并不那么简单。这是我到目前为止所尝试过的,我还没有在谷歌网上找到任何结合整数和浮点数加法或减法的东西,因为我将同时执行这两项操作——

我需要保持正在处理的总 MB 数和保存的总 MB 数 - 因此需要同时添加和减去浮点数和整数,以及将它们一起减去。

#! /bin/bash


# I've tried with and without using this typeset to integer
# even though float won't work with integer -- just ball parking 
# and googling - :\

# typeset -i MB1 MB2


# using EXIFTOOL to get the megabytes off of files then add and subtract
# the values is what I need to do


FileSize1="`exiftool '-File Size'  "The Motels - Careful.mp3" -p   '$FileSize'`"


MB1="${FileSize1% *}" # removes the MB and leaves just the numbers both
                      # integer and float with demimal point - 3.3 



FileSize2="`exiftool '-File Size'  "02 Only The Lonely.flac" -p '$FileSize'`"

MB2="${FileSize2% *}"

echo "$FileSize1"
echo "$MB1"
echo "$FileSize2"
echo "$MB2"

6.4 MB
6.4
19 MB
19

total=`echo $MB1 + $MB2 | bc`  

echo $total  "   total"

# error message here is: 
# ./getMB: line 20: 6.4+19: syntax error: invalid arithmetic operator (error token is ".4+19")

answer=$(($MB1+$MB2)) # doesn't work

echo "$answer" " -- answer=="

# error message : line 16: 6.4+19: syntax error: invalid arithmetic operator (error token is ".4+19")

answer=`expr $MB1 + MB2`

echo "$answer" " -- answer=="

# error message : expr: non-integer argument

# then added typeset -i MB1 MB2
# then I get this error message
# ./getMB: line 7: ���������
# : 6.4: syntax error: invalid arithmetic operator (error token is ".4")

echo "$answer" " -- answer=="

答案1

使用 bc 进行浮点和整数基本数学运算,在循环中保持运行计数

#!/bin/bash

#variable to keep changing amount
#declared outside of loop before it
#runs

changeVal=0



while amount < stopPoint ; do

# get the MB of orginal file
FileSize1="`exiftool '-File Size'  "$FILENAME" -p '$FileSize'`"

#re-sampling mp3 code here 
 lame what ever args firstFileName endFileName

# get the MB of new file
FileSize2="`exiftool '-File Size'  "$FILENAME" -p '$FileSize'`"

# strip off the 'MB' leaving just the values
MB1="${FileSize1% *}"
MB2="${FileSize2% *}"


# out put formatted by using spaces 
echo "  "$MB1"  MB1 - start size"
echo "- "$MB2"  MB2 - ending size"
#holds remaining value 
totalSaveOnFile=`echo $MB1 - $MB2 | bc`
echo "----------"
echo "  "$totalSaveOnFile" regained space" 
 #keeps last total -- then adds it to a new remaining value
 # giving a new tally of total 
 maxSaved=`echo $totalSaveOnFile + $maxSaved | bc`

 echo "  "$maxSaved " Total space saved do far"

 let amount++
 done 

循环不可运行——但是保持运行计数的代码是很好的代码——在我弄清楚如何使用 bc 后,我自己测试了它,感谢 @glenn jackman 向我指出了它。

maxSaved=`echo $totalSaveOnFile + $maxSaved | bc`

TotalSaveOnFile 保存旧文件和重新采样的文件大小之间的差异的新总计,然后通过将变量中已有的内容添加到其自身和新的totalSaveOnFile 变量来添加到 maxSaved,以给出新的总金额HDD 上节省的空间。同时使用浮点值和整数值。

相关内容