shell脚本测试

1.判断输入是否是数字,并且输出简单图形

#!/bin/bash
# read -r 指定读取命令把一个 \ (反斜杠) 处理为输入行的一部分,而不把它作为一个控制字符。
read -r -p "input a num: " num 
#判断输入是否是数字,直到输入正确数字为止
flag=true
while $flag
do
if [ -n "$num" ];then
   test=$(echo "$num"|sed 's/[0-9]//g')
   if [ -z "$test" ];then
   flag=false   
   fi
fi
[ "$flag" == "false" ] || read -p "input correct num: " num
done

#输出简单队列形状
for (( i=1;i<=$num;i++ ))
  do 
   for j in $(seq 1 $i)
     do
     echo -n "*"
     done
   echo
  done

echo "############"

for (( i=$num;i>=1;i-- ))
  do 
   for j in $(seq 1 $i)
     do
     echo -n "*"
     done
   echo
  done
使用函数写法循坏判断是否是数字,直到输入数字为止:
#!/bin/bash
function fcheck(){
if [ -n "$1" ];then
   test=$(echo "$1"|sed 's/[0-9]//g') 
   if [ -z "$test" ];then
      echo $1
   else
      read -r -p "input correct num: " num
      fcheck "$num"
   fi
fi
}
read -r -p "input a num: " num
fcheck "$num"

2.测试结果:

3.打印Fibonacci数列:

使用shell:

#!/bin/bash
t1=0
t2=1
read -p "plz input a number: " n
out="$t1+$t2"
for(( i=2;i<$n;i++ ))
  do
      next=$(( $t1 + $t2 ))
      t1=$t2
      t2=$next;
      out="$out+$next"
  done
echo "Fibonacci Series:$out"

 测试结果:

[root@rhel64-64bit Desktop]# bash test.sh
plz input a number: 12
Fibonacci Series:0+1+1+2+3+5+8+13+21+34+55+89

使用c语言:

#include <stdio.h>
int main()
{
  int i, n, t1=0, t2=1, next=0;
  printf("Enter number: ");
  scanf("%d",&n);
  printf("Fibonacci Series: %d+%d", t1, t2); 
  for(i=2;i<n;i++)
  {
      next=t1+t2;
      t1=t2;
      t2=next;
      printf("+%d",next);
  }
  printf("\n");
  return 0;
}

测试结果:

[root@rhel64-64bit Desktop]# gcc test.c
[root@rhel64-64bit Desktop]# ./a.out
Enter number: 12
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89
[root@rhel64-64bit Desktop]# 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值