以下程序在第 7 行和第 9 行出现错误:while
循环似乎不起作用。这是一个显示从 3 到所需给定输入的所有质数和合数的程序。
echo prograam to find all the prime numbers from 3 to given number
echo enter the last number
read number
n=$number
i=3
m=3
while [ $m -le $n ]
do
while [ $i -le $m ]
do
m=`expr $n % $i`
i=`expr $i +1`
if [ $m -eq 0 ]
then
echo $n is a prime number \n
else
echo $n is not a prime number \n
fi
done
m=`expr $m +1`
done
答案1
答案2
为您重写了 shell 脚本:
echo "program to find all the prime numbers from 3 to given number"
echo "enter the last number"
read number
n=$number
i=2
m=2
is_prime=0
while [ "$m" -lt "$n" ]
do
while [ "$i" -le "$m" ]
do
m=$(expr $n % $i)
i=$(expr $i + 1)
if [ "$m" -eq 0 ]
then
echo "$n is not a prime number"
exit
else
is_prime=1
fi
done
m=$(expr "$m" + 1)
done
if [ "$is_prime" -eq 1 ]; then
echo "$n is a prime number"
fi
exit
为此,参考了以下内容:
答案3
除了 Radu 已经指出的脚本中的语法错误外,还有一些逻辑错误。我给你的是精炼代码。它将断言某个数字是否为素数或不在范围内
#!/bin/bash
echo "prograam to find all the prime numbers from 3 to given number"
echo "enter the last number: "
read number
m=3
while [ $m -le $number ]
do
i=2
flag=0
while [ $i -lt $m ]
do
if [ `expr $m % $i` -eq 0 ]
then
echo "$m is not a prime number"
flag=1
break
fi
i=`expr $i + 1`
done
if [ "$flag" = 0 ]; then
echo "$m is a prime number"
fi
m=`expr $m + 1`
done
我引入了一个新变量flag
来正确打印出数字。将脚本保存为check_prime.sh
并授予其执行权限。
输出
$ ./check_prime.sh
prograam to find all the prime numbers from 3 to given number
enter the last number:
12
3 is a prime number
4 is not a prime number
5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number