题目1:1-100求和
非递归版本:
#!/bin/bash sum=0 while [ $val -le 100 ] do let sum+=val let val++ done echo $sum sum=0 for i in {1..100} do if [ $i == 1 ]; then bar=${bar}${i} else bar=${bar}+${i} fi let sum+=i done echo $bar=$sum sum=0 for (( i=1 ; i<=100 ; i++)) do let sum+=i done echo $sum
运行结果:
递归版本:
#!/bin/bash function add() { local count=$1 if [ $count -eq 1 ];then echo 1 return fi local tmp=$count let --tmp local ret=`add $tmp` let ret+=count echo $ret } read c ret=$(add $c) echo "$ret"
运行结果:
bc计算:
2字符串转换,前后数字转换,字母大小写转换:
#!/bin/bash function str() { while read str do str1=`echo ${str:0:3}` str2=`echo ${str:3:3} | tr ‘[a-z]‘ ‘[A-Z]‘` str3=`echo ${str:6:3}` printf "%s%s%s\n" "$str3" "$str2" "$str1" done<file } str
运行结果:
之前:
753asd456
789dfg123
789fdh456
改变后:
求文件中行代表数字的最大值最小值:
#!/bin/bash read name avg=0 max=0 min=0 cur=0 sum=0 count=0 #cat $name | while read line while read line do let cur=$line if [ $count -eq 0 ];then max=$line min=$line fi if [ $cur -gt $max ];then max=$cur fi if [ $cur -le $min ];then min=$cur fi let count++ let sum+=cur done<$name echo "MAX:$max" echo "MIN:$min" echo "SUM:$sum COUNT:$count" echo "average: $((sum/count))"
运行结果:
进度条:
斐波那契数列:
#!/bin/bash arry[0]=1 arry[1]=2 temp=0 sum=0 for i in {0..99} do if [ $i -gt 0 ];then let arry[$i+1]=arry[$i]+arry[$i-1] fi done echo ${arry[99]}
运行结果:
时间: 2024-10-08 22:23:03