英文:
given input a sequence to determine if it is increasing or decreasing
问题
user insert: 1 2 4
system response: 这个序列是递增的
user insert: 4 3 2
system response: 这个序列是递减的
英文:
hi given a sequence I have to check if it is increasing or decreasing, I did it but it doesn't work for me how can I solve it?
#!/bin/bash
tot=0
numeri=0
media=0
cresc=0
decresc=0
for number in $@
do
tot=$((tot+number))
numeri=$((numeri+1))
done
echo TOTALE = $tot
media=$((tot/numeri))
echo MEDIA = $media
if [ $cresc -eq 0 ]
then echo SEQ. CRESCENTE
else echo SEQ. DECRESCENTE
fi
output:
user insert: 1 2 4
system response: the sequence is increasing
user insert: 4 3 2
system response: the sequence is decreasing
答案1
得分: 1
这个简单而易读的是怎么样的?
#!/bin/bash
crescente=0
decrescente=${#@}
dec=$decrescente
for number; do
if [[ ! $number =~ ^-?[0-9]+$ ]]; then
echo "C'È ALMENO QUALCOSA CHE NON È UN NUMERO" >&2
exit 1
fi
if [[ $last ]]; then
if ((last < number)); then
((crescente++))
elif ((last > number)); then
((decrescente++))
fi
fi
last=$number
done
if ((crescente && decrescente == dec)); then
echo "SEQ. CRESCENTE"
elif ((descrecente < dec && crescente == 0)); then
echo "SEQ. DECRESCENTE"
else
echo "NON ORDINATO" >&2
exit 1
fi
((...))
是一个算术命令,如果表达式非零,则返回退出状态 0,如果表达式为零,则返回退出状态 1。还可用作 "let" 的同义词,如果需要副作用(赋值)。请参见http://mywiki.wooledge.org/ArithmeticExpression。
示例输出
$ ./seq.sh 1 2 x
C'È ALMENO QUALCOSA CHE NON È UN NUMERO
$ ./seq.sh 1 2 3
SEQ. CRESCENTE
$ ./seq.sh 3 2 1
SEQ. DECRESCENTE
$ ./seq.sh 3 2 1 0
SEQ. DECRESCENTE
$ ./seq.sh 3 2 1 0 -1
SEQ. DECRESCENTE
$ ./seq.sh -42 42 $((2**42))
SEQ. CRESCENTE
$ ./seq.sh 3 5 2
NON ORDINATO
英文:
What about this simple and readable one?
#!/bin/bash
crescente=0
decrescente=${#@}
dec=$decrescente
for number; do
if [[ ! $number =~ ^-?[0-9]+$ ]]; then
echo "C'È ALMENO QUALCOSA CHE NON È UN NUMERO" >&2
exit 1
fi
if [[ $last ]]; then
if ((last < number)); then
((crescente++))
elif ((last > number)); then
((decrescente++))
fi
fi
last=$number
done
if ((crescente && decrescente == dec)); then
echo "SEQ. CRESCENTE"
elif ((descrecente < dec && crescente == 0)); then
echo "SEQ. DECRESCENTE"
else
echo "NON ORDINATO" >&2
exit 1
fi
((...))
is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See <http://mywiki.wooledge.org/ArithmeticExpression>.
Example output
$ ./seq.sh 1 2 x
CÈ ALMENO QUALCOSA CHE NON È UN NUMERO
$ ./seq.sh 1 2 3
SEQ. CRESCENTE
$ ./seq.sh 3 2 1
SEQ. DECRESCENTE
$ ./seq.sh 3 2 1 0
SEQ. DECRESCENTE
$ ./seq.sh 3 2 1 0 -1
SEQ. DECRESCENTE
$ ./seq.sh -42 42 $((2**42))
SEQ. CRESCENTE
$ ./seq.sh 3 5 2
NON ORDINATO
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论