所以我在linux终端上编写程序,我的程序有两个部分。第一部分是划分,第二部分是计算某些数字的MOD。退出第一部分的方法是将999放入任何一个输入中以进行除法。
我的问题是,即使用户输入999作为第一个输入,用户也必须输入第二个数字。我想知道这些是不是像windows中的那样你可以在linux中执行goto:someOtherLocation。这是代码:
echo "Enter the number to divide (dividend) (enter 999 to quit):"
read numberOne
[IF NUMBERONE = 999, JUMP TO SECONDPART]
echo "Enter the number to divide (divisor) (enter 999 to quit):"
read numberTwo
while [ "$numberOne" -ne '999' ] && [ "$numberTwo" -ne '999' ]
do
while [ "$numberTwo" -eq 0 ]
do
echo "You cannot divide by 0, please enter another number:"
read numberTwo
done
RESULT=$(echo "$numberOne/$numberTwo" | bc -l)
echo $numberOne / $numberTwo = $RESULT
echo $numberOne / $numberTwo = $RESULT >> results.txt
echo "Enter the number to divide (dividend) (enter 999 to quit):"
read numberOne
echo "Enter the number to divide (divisor) (enter 999 to quit):"
read numberTwo
done
SECONDPART
counter=1
totalCount=0
temporal=0
while [ "$counter" -lt '101' ]
do
temporal=$( expr $counter % 5)
echo $counter MOD 5 = $temporal
echo $counter MOD 5 = $temporal >> results.txt
totalCount=$(echo "$totalCount+$temporal" | bc -l)
counter=$(echo "$counter+1" | bc -l)
done
average=$(echo "$totalCount/100" | bc -l)
echo The average of all the MODs is $average >> results.txt
如上所示,如果输入为999,我想直接从输入跳转到第二部分。
答案 0 :(得分:3)
像sh
和bash
这样的Bourne shell没有GOTO语句。这是considered harmful。
相反,使用结构化流程控制,如if语句:
echo "Enter the number to divide (dividend) (enter 999 to quit):"
read numberOne
if [ "$numberOne" -ne 999 ]
then
echo "Enter the number to divide (divisor) (enter 999 to quit):"
read numberTwo
while [ "$numberOne" -ne '999' ] && [ "$numberTwo" -ne '999' ]
do
while [ "$numberTwo" -eq 0 ]
do
echo "You cannot divide by 0, please enter another number:"
read numberTwo
done
RESULT=$(echo "$numberOne/$numberTwo" | bc -l)
echo $numberOne / $numberTwo = $RESULT
echo $numberOne / $numberTwo = $RESULT >> results.txt
echo "Enter the number to divide (dividend) (enter 999 to quit):"
read numberOne
if [ "$numberOne" -ne 999 ]
then
echo "Enter the number to divide (divisor) (enter 999 to quit):"
read numberTwo
fi
done
fi
counter=1
totalCount=0
temporal=0
while [ "$counter" -lt '101' ]
do
temporal=$( expr $counter % 5)
echo $counter MOD 5 = $temporal
echo $counter MOD 5 = $temporal >> results.txt
totalCount=$(echo "$totalCount+$temporal" | bc -l)
counter=$(echo "$counter+1" | bc -l)
done
average=$(echo "$totalCount/100" | bc -l)
echo The average of all the MODs is $average >> results.txt
它可能看起来比一个简单的goto更尴尬,但是当你利用更结构化的控制流时,代码变得更容易阅读和遵循:
readNumber() {
local number
read -p "$1" number
[ "$number" -ne 999 ] && echo "$number"
}
while one=$(readNumber "Enter dividend or 999 to quit: ") && \
two=$(readNumber "Enter divisor or 999 to quit: ")
do
echo "$one / $two = $(echo "$one / $two" | bc -l)" | tee results.txt
done
这一直要求分数,直到用户为其中任何一个输入999。
答案 1 :(得分:2)
您也可以这样做(bash示例):
#!/bin/bash
secondpart() {
echo "Hello"
}
read x
if [ $x -eq 999 ]
then
secondpart
else
echo "Bye"
fi
现在,当您运行代码时,如果您的输入为999
,则程序将返回Hello
,否则返回将为Bye
。