好的,这是我的代码,您可能可以了解我想要做的事情的要点。我不太擅长 Linux bash。
#random numbers
MAXCOUNT=100
count=1
while [ "$count" -le $MAXCOUNT ]; do
number[$count]=$RANDOM
let "count += 1"
done
#adding function
function sum()
{
echo $(($1+$2))
}
#main section
first="${count[1-20]}"
echo "The sum of the first 20 elements are: $first"
last="${count[1-20]}"
echo "The sum of the last 20 elements is: $last"
if [ $first -gt $last ]; then
echo "The sum of the first 20 numbers is greater."
else
echo "The sum of the last 20 numbers is greater."
fi
我使用这个脚本的目标:
获取并回显包含随机数的数组的前 20 个数字的总和。
获取并回显包含随机数的数组的最后 20 个数字的总和。
回显第一个和是否大于第二个和。
任何帮助都会很棒!请猛击。
答案1
让我们从求和函数开始。我们实际上想让它更通用一些——让它添加所有参数,这样我们就可以摆脱几个循环做类似的事情reduce func array
。
# Since you are using bash, let's use declare to make things easier.
# Don't use those evil `function foo` or `function foo()` stuffs -- obsolete bourne thing.
sum(){ declare -i acc; for i; do acc+=i; done; echo $acc; }
剩下的就很容易了。
MAXCOUNT=100 num=()
# Let's use the less evil native 0-based indices.
for ((i=0; i<MAXCOUNT; i++)); do nums+=($RANDOM); done
# https://gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
# set f to the sum of the 20 elements of nums starting from elem 0
f=$(sum "${nums[@]:0:20}"); echo f20=$f
# set l to the sum of the LAST 20 elems of nums, mind the space
l=$(sum "${nums[@]: -20}"); echo l20=$l
if ((f > l)); then echo f20g; else echo l20g; fi
答案2
unset num[@] sum; c=-1
while num[c+=1]=$RANDOM
do case $c in ([2-7]?) ;;
($((sum+=num[c])):|99) ! eval '
printf "$@$sum" "$'"$((sum<$3?2:4))\" greater";;
(19) set "The sum of the %-5s 20 elements is:\t%s\n" \
first "$sum" last ""; sum=0
esac||break
done
The sum of the first 20 elements is: 308347
The sum of the last 20 elements is: 306596
The sum of the first 20 elements is: greater
答案3
另一种可能的解决方案:
#!/bin/bash
max=100 rng=20 ### Problem conditions
texta="The sum of the %.3sst %d elements is: %d\n" ### Output
textb="The first sum is %ser than the last sum\n" ### Output
unset num ### used vars
for (( s1=s2=c=0 ; c<max ; c++ ))
do num[c]=$RANDOM
(( c<rng )) && (( s1+=num[c] )) ### first sum.
(( c>=max-rng )) && (( s2+=num[c] )) ### last sum.
done
compare=small; (( s1 > s2 )) && compare=bigg
printf "$texta" "first" "$rng" "$s1"
printf "$texta" " last" "$rng" "$s2"
printf "$textb" "$compare"
The sum of the first 20 elements is: 348899
The sum of the last 20 elements is: 336364
The first sum is bigger than the last sum