【问题标题】:Loop on Unix, basic calculator of geometric figuresUnix 上的循环,几何图形的基本计算器
【发布时间】:2018-05-06 14:29:23
【问题描述】:

我正在尝试创建一个几何图形计算器,但我遇到了一个循环。我在 shell 脚本中使用菜单,到目前为止还没有运气。

可以请人帮我吗?

当前脚本是:

#!/bin/bash

echo "Welcome, please enter username:"

read $username

echo "WELCOME  $( getent passwd "$USER" | cut -d: -f5 | cut -d, -f1), This is a basic calculator of square,circle and rectangle. "


echo  "Please choose from 1,2 or 3 to continue: " 

echo "1. Rectangle"
echo "2. Circle"
echo "3. Square"
echo "4. Quit"

read choice

if [ $choice -eq 1 ]
then
echo "You choose rectangle"
echo "Enter the height:"
read height
echo "Enter the width:"
read width
area=`echo "$height * $width"|bc`
echo "The area of the rectangle is:"$area

else
if [ $choice -eq 2 ]
then
echo "You choose circle"
echo "Enter the radius of the circle:"
read radius
area1=`echo "3.141 * $radius * $radius"|bc`
echo "The area of the circle is:"$area1

else
if [ $choice -eq 3 ]
then
echo "You choose square"
echo "Enter the width of the square:"
read w
area2=`echo "$w * $w"|bc`
echo "The area of the circle is:"$area2

else
If [ $choice -eq 4 ]
then "You choose quit"

"Quit")
            break
            ;;
        *) echo invalid option;;

如您所见,我不知道如何停止循环并“退出”。

谢谢!

【问题讨论】:

  • 格式化您的问题会更容易理解和回复。您可以先在每行代码前输入 4 个空格...
  • @rainer 或者直接点击{} 按钮而不是手动输入空格。
  • 你在说什么循环?我在您的代码中没有看到循环。
  • 如果我选择任何选项 netween1 2 3 我可以进行几何计算。从那里我无法退出计算。我需要添加退出选项和选择另一个选项的方法。

标签: linux bash loops unix


【解决方案1】:
#!/bin/bash

echo "Welcome, please enter username:"

read $username

echo "WELCOME  $( getent passwd "$USER" | cut -d: -f5 | cut -d, -f1), This is a basic calculator of square,circle and rectangle. "

while true
do
echo  "Please choose from 1,2 or 3 to continue: " 

echo "1. Rectangle"
echo "2. Circle"
echo "3. Square"
echo "4. Quit"

read choice

if [ $choice -eq 1 ]
then
    echo "You choose rectangle"
    echo "Enter the height:"
    read height
    echo "Enter the width:"
    read width
    area=`echo "$height * $width"|bc`
    echo "The area of the rectangle is:"$area

elif [ $choice -eq 2 ]
then
    echo "You choose circle"
    echo "Enter the radius of the circle:"
    read radius
    area1=`echo "3.141 * $radius * $radius"|bc`
    echo "The area of the circle is:"$area1

elif [ $choice -eq 3 ]
then
    echo "You choose square"
    echo "Enter the width of the square:"
    read w
    area2=`echo "$w * $w"|bc`
    echo "The area of the circle is:"$area2

elif [ $choice -eq 4 ]
then 
    break
else 
    echo "invalid option"
fi
done

我想你想这样做。这将无限循环,直到您按 4。

【讨论】:

  • 是的,这就是我想做的!谢谢!
猜你喜欢
  • 2017-11-25
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多