【问题标题】:How can I use a while loop to execute this code properly in UNIX?如何在 UNIX 中使用 while 循环正确执行此代码?
【发布时间】:2015-04-07 19:05:06
【问题描述】:
echo -n "Enter a positive integer: "; read integer
  While [ $integer -gt 0 ]; do
    echo "$integer"
  done

我正在尝试在 UNIX 中编写满足以下条件的脚本:

  1. 将脚本命名为while.sh
  2. 要求用户输入一个正整数。您可以假设用户将输入一个正整数(不需要输入验证)。
  3. 使用 while 循环打印从 0 到输入的整数(包括输入的整数)的所有整数。

前两个步骤很简单,但我无法正确执行第三步。谁能帮帮我?

【问题讨论】:

  • 使用expr 增加一个变量:x=`expr $x + 1`
  • 你需要一个“计数器”变量,它从 0 开始,当大于用户的值时停止。
  • 我不知道expr命令,以后会有用的,谢谢你的输入。
  • 不要使用expr 进行整数运算;使用 POSIX 算术表达式; x=$((x + 1)).

标签: linux shell unix


【解决方案1】:

这是你想要的脚本:

#!/bin/bash

echo -n "Enter a positive integer: "; read integer
while [ $integer -gt 0 ]; do
    echo "$integer"
    integer=`expr $integer - 1`
done

这是一个例子:

./while.sh 
Enter a positive integer: 10
10
9
8
7
6
5
4
3
2
1

【讨论】:

  • 或者干脆((--integer))
  • 你就是炸弹!非常感谢。
  • ((--integer)) 不是标准的 shell 命令;只有一些 shell 会支持它。相反,使用integer=$((integer - 1)) 甚至: $((--integer))
【解决方案2】:

这是我想出的脚本。我可能把这理解为有点字面意思,但是您的问题确实要求在输入的数字上显示 0。

#! /bin/bash

i=0

echo -n "Enter a positive integer: "
read integer

while [ $integer -ge $i ]
 do
  echo "$i"
  ((i++))
done

这是上面的输出:

Enter a positive integer: 11
0
1
2
3
4
5
6
7
8
9
10
11

【讨论】:

  • 这是另一种思考方式。我喜欢你的方式,因为它是升序,而不是降序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2019-06-20
  • 1970-01-01
相关资源
最近更新 更多