循环检查用户定义数字的倍数是否在用户定义的范围内

loop to check if the multiples of a user defined number are even within a user defined range

大家好,我正在尝试在 bash 中编写一个脚本,它将采用用户定义的数字和 运行 它的倍数,然后检查其中哪些倍数是偶数,并仅在用户定义的范围。 and the script seems to be working when an even number is selected as the value but when an odd number is selected it only prints out half of the numbers you wish to see.我想我知道为什么会发生它与我的 while 语句有关 $mult -le $range 但我不确定如何解决这个问题或如何让它显示基于偶数和奇数的完整范围数字。感谢任何帮助。

代码

#!/bin/sh
echo "Please input a value"
read -r val
echo "Please input how many multiples of this number whose term is even you wis>
read -r range
mult=1
while [ $mult -le $range ]
do
        term=$(($val*$mult))
        if [[ $(($term % 2)) -eq 0 ]]
                then echo "$term"
        fi
((mult++))
done
echo "For the multiples of $val these are the $range who's terms were even"

输出偶数

$ ./test3.sh
Please input a value
8
Please input how many multiples of this number whose term is even you wish to see
4
8
16
24
32
For the multiples of 8 these are the 4 whose terms were even

输出奇数

$ ./test3.sh
Please input a value
5
Please input how many multiples of this number whose term is even you wish to see
10
10
20
30
40
50
For the multiples of 5 these are the 10 whose terms were even

您当前的while条件假设val小于或等于val * range的偶数倍数至少为range。事实上,对于偶数,有恰好range个小于等于val * range的偶数倍数。奇数不是这种情况 - 正如您遇到的那样。

您需要引入一个新变量来解决这个问题 - 一个跟踪您到目前为止遇到的偶数倍数的变量。一旦达到所需的数量,循环就会终止。

所以,您可以先设置一个计数器

count=0

并在你的 while 循环条件中检查这个

while [ $count -lt $range ]

每次进入 if 的主体时,您都会增加 count - 即每当遇到偶数时。

这应该会给你想要的行为。