1. Calculate the sum of all integers from 1 to 100
for loop method:
#!/bin/bash
sum=0
for (( i=1; i<=100; i++ ))
do
let sum=$i+$sum
done
echo $sum
while loop method:
#!/bin/bash
a=1
b=100
sum=0
while [[ $a -le $b ]]
do
let sum=$a+$sum
let a++
done
echo $sum
2. Prompt the user to enter an integer less than 100, and calculate the sum of all integers from 1 to this number
for loop method:
#!/bin/bash
sum=0
b=1
read -p "请输入小于100的整数" w
for (( i=0; i<$w; i++ ))
do
let sum=$b+$sum
let b++
done
echo $sum
while loop method:
#!/bin/bash
sum=0
a=0
read -p "请输入一个小于100的整数" w
while [ $a -le $w ]
do
let sum=$a+$sum
let a++
done
echo $sum
Three, find the even and odd sums of all integers from 1 to 100
for loop method:
#!/bin/bash
os=0
js=0
for ((i=1; i<=100; i++))
do
a=$[$i % 2]
if [ $a == 0 ]
then
let os=$os+$i
elif [ $a == 1 ]
then
let js=$js+$i
fi
done
echo "奇数和为$js"
echo "偶数和为$os"
while loop method:
#!/bin/bash
os=0
js=0
i=1
while [[ $i -le 100 ]]
do
a=$[$i % 2]
if [ $a == 0 ]
then
let os=$os+$i
elif [ $a == 1 ]
then
let js=$js+$i
fi
let i++
done
echo "奇数和为$js"
echo "偶数和为$os"
Four, nested loop questions:
Each store has five kinds of goods to buy (clothes 500 yuan, pants 400 yuan, shoes 350 yuan, hats 150 yuan, socks 50 yuan), each time the purchase is completed or not, the user will be prompted whether to continue to the next store, if If you don’t continue shopping, the shopping cart will settle the total amount.
#!/bin/bash
yf=500
kz=400
xz=350
mz=150
wz=50
gwc=0
b=0
echo "欢迎光临本店,请选择你需要的商品"
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
while [ $b -eq 0 ]
do
read -p "请选择您需要的商品:" sp
if [ $sp -eq "1" ]
then
let gwc=$gwc+$yf
echo "您当前消费$gwc"
read -p "您是否需要继续购物(y/n)" gw
if [ $gw == "n" ]
then
echo "您结算的金额是$gwc"
break
fi
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
elif [ $sp -eq "2" ]
then
let gwc=$gwc+$kz
echo "您当前消费$gwc"
read -p "您是否需要继续购物(y/n)" gw2
if [ $gw2 == "n" ]
then
echo "您结算的金额是$gwc"
break
fi
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
elif [ $sp -eq "3" ]
then
let gwc=$gwc+$xz
echo "您当前消费$gwc"
read -p "您是否需要继续购物(y/n)" gw3
if [ $gw3 == "n" ]
then
echo "您结算的金额是$gwc"
break
fi
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
elif [ $sp -eq "4" ]
then
let gwc=$gwc+$mz
echo "您当前消费$gwc"
read -p "您是否需要继续购物(y/n)" gw4
if [ $gw4 == "n" ]
then
echo "您结算的金额是$gwc"
break
fi
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
elif [ $sp -eq "5" ]
then
let gwc=$gwc+$wz
echo "您当前消费$gwc"
read -p "您是否需要继续购物(y/n)" gw5
if [ $gw5 == "n" ]
then
echo "您结算的金额是$gwc"
break
fi
echo "1:衣服500,2:裤子400,3:鞋子350,4:帽子150,5:袜子50"
fi
done