shell脚本实例之Charpter8-14

本文介绍了一个使用Bash脚本语言实现的功能,该功能通过while循环处理用户输入的两个整数,输出两数间的奇数及偶数之和。文章提供了详细的脚本示例并展示了如何运用数组和条件判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


要求:使用while循环编写脚本,使其完成以下功能:

1.提示用户输入两个整数:firstNum和secondNum(firstNum的值一定要小于secondNum)

2.输出所有介于这两数之间的奇数

3.输出所有介于这两数目之间偶数之和


先看一下如何用for循环实现:

#!/bin/bash
#chapter_8-14

echo "Please input two integer numbers(the first must be smaller than the second):"

read firstNum secondNum

#定义函数fun0,判断输入的两个数的大小
fun0()
{
   while [ $1 -lt $2 ]
    do
       echo "Your input:" "$firstNum ""$secondNum"
       break
   done
}

fun0 $firstNum $secondNum

#定义一个数组,将两个数之间的所有数写入数组
declare -a arr1
i=firstNum
arr1=($(
for ((i=firstNum;i<=secondNum;i++))
do
   echo -n "$i "
done
))

length=${#arr1[@]}
sum_even=0

if [[ "arr1[0]%2" -eq 0 ]]
then
    for ((j=0;j<=length;j=j+2))
    do
      let   sum_even+=arr1[j]
      echo -n "${arr1[j+1]} "
    done
    echo "偶数之和为:" $sum_even
else
    for ((k=0;k<=length;k=k+2))
    do
       let  sum_even+=arr1[k+1]
       echo -n "${arr1[k]} "
    done
    echo "偶数之和为:" "$sum_even "
fi

脚本执行效果:

[root@localhost charpter8]# sh 8-14
Please input two integer numbers(the first must be smaller than the second):
3 29
Your input: 3 29
3 5 7 9 11 13 15 17 19 21 23 25 27 29 偶数之和为: 208
[root@localhost charpter8]# sh 8-14
Please input two integer numbers(the first must be smaller than the second):
8 29
Your input: 8 29
9 11 13 15 17 19 21 23 25 27 29  偶数之和为: 198


while 循环实现:

#!/bin/bash

echo "Pleas input two integer number(the first num must be smaller than the second one):"
read firstNum secondNum

fun0()
{
  while [ $1 -lt $2 ]
  do
      echo "Your input is:" "$firstNum " "$secondNum"
      break
  done
}

fun0 $firstNum $secondNum

declare -a arr1
let i=firstNum
arr1=(
      $(
        while ((i<=secondNum))
        do
                echo "$i "
                let i++
        done
      )
)

length=${#arr1[@]}
j=0
k=0
sum_even=0
if [[ "arr1[0]%2" -eq 0 ]]
then
        while ((j<length))
        do
                echo -n "${arr1[j+1]} "
                let sum_even+=arr1[j]
                let j=j+2
        done
        echo "偶数之和:$sum_even"
else
        while ((k<length))
        do
                echo -n "${arr1[k]} "
                let sum_even+=arr1[k+1]
                let k=k+2
        done
        echo  "偶数之和:$sum_even"
fi


脚本执行效果:

root@localhost charpter8]# sh 8-14-1
Pleas input two integer number(the first num must be smaller than the second one):
31 38
Your input is: 31  38
31 33 35 37 偶数之和:140
[root@localhost charpter8]# sh 8-14-1
Pleas input two integer number(the first num must be smaller than the second one):
30 39
Your input is: 30  39
31 33 35 37 39 偶数之和:170


两种循环实现发现大致相似.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值