我想编写一个脚本,从标准输入获取其参数(每天的学习时间)并检查学生是否定期学习。定期学习是指学生连续7天每天至少学习4小时,并且这7天中至少2天每天至少学习6小时(这不必是连续的)。我试过这个:
four_h=0
six_h=0
for i in $@ ; do
if [ $i -ge 6 ]; then let six_h=six_h+1
elif [ $i -ge 4 ]; then let four_h=four_h+1
else :
fi
done
if [ $four_h -ge 7 ] && [ $six_h -ge 2 ];
then echo "you are regularly studying"
else echo "you are not regularly studying"
fi
但它不起作用。我想我无法迭代,但不明白为什么。另外我不知道如何检查学生是否“连续”学习超过4小时。
答案1
听起来您必须确保满足两个条件:
- 任意 7 个连续值中的所有数字都必须为 4 或更大。
- 任意 7 个连续数字中的两个数字必须至少为 6。
因此,您似乎必须保留一个数字数组,并且需要从该数组恰好包含 7 个数字时开始检查这两个条件。
之后,您可以开始替换以循环方式读取数组中的数字,并针对每个新数字再次检查条件。
下面的bash
脚本就是这样做的。正如这个出现作为一个家庭作业问题,除了代码中的注释所说之外,我不会再多说什么。考虑一下,如果在不知道代码的作用的情况下使用它作为家庭作业的答案,你会对自己造成伤害。如果代码的质量与您或您的同事所看到的不同,您也可能会因作弊而被指责。
#!/bin/bash
has_studied () {
# Tests the integers (given as arguments) and returns true if
# 1. All numbers are 4 or larger, and
# 2. There are at least two numbers that are 6 or greater
local enough large
enough=0 large=0
for number do
[ "$number" -ge 4 ] && enough=$(( enough + 1 ))
[ "$number" -ge 6 ] && large=$(( large + 1 ))
done
# Just some debug output:
printf 'Number of sufficient study days: %d\n' "$enough" >&2
printf 'Number of long study days (out of those): %d\n' "$large" >&2
[ "$enough" -eq 7 ] && [ "$large" -ge 2 ]
}
# Array holding the read integers
ints=()
echo 'Please enter hours of study, one integer per line' >&2
echo 'End by pressing Ctrl+D' >&2
# Loop over standard input, expecting to read an integer at as time.
# No input validation is done to check whether we are actually reading
# integers.
while read integer; do
# Add the integer to the array in a cyclic manner.
ints[i%7]=$integer
i=$(( i + 1 ))
# If the array now holds 7 integers, call our function.
# If the function returns true, continue, otherwise terminate
# with an error.
if [ "${#ints[@]}" -eq 7 ]; then
if ! has_studied "${ints[@]}"; then
echo 'Has not studied!'
exit 1
fi
fi
done
# If the script hasn't terminated inside the loop, then all input has
# been read and the student appears to have studied enough.
echo 'Appears to have studied'
答案2
awk
读取的版本stdin
awk 'BEGIN{print "Enter study hours and finish input with ctrl+d:"}
{if ($0 >=0) {count++; print $0" hours on day "count}
if ($0 >= 4 && $0 < 6) hrs[4]++;
if ($0 >= 6) hrs[6]++}
END{print "\nStudy scheme over "count" days:";
for (d in hrs) print d" hours studied on "hrs[d]" days";
if (hrs[4]+hrs[6] < 7 || hrs[6] < 2) not=" not";
print "You are"not" studying regularly"
}' -