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]#