linux写出一段SHELL脚本,实现1+2+3+...100
时间: 2023-09-18 10:12:15 浏览: 63
好的,以下是一段实现1+2+3+...+100的SHELL脚本:
```bash
#!/bin/bash
sum=0
for ((i=1; i<=100; i++))
do
sum=$((sum+i))
done
echo "1+2+3+...+100 = $sum"
```
运行该脚本,输出结果为:
```
1+2+3+...+100 = 5050
```
解释一下脚本的实现过程:
1. 在第2行,我们定义了一个变量`sum`,用于储存1+2+3+...+100的结果;
2. 在第4-7行,我们使用了一个for循环,从1循环到100,每次将循环变量`i`加到`sum`中;
3. 在第9行,我们使用`echo`命令输出计算结果。
这样就完成了1+2+3+...+100的计算,希望能对你有所帮助!
相关问题
编写一个shell脚本计算1+2+3+...+100
以下是两种编写shell脚本计算1+2+3+...+100的方法:
方法1:
```shell
sum=0
i=0
while ((i<=100))
do
sum=$(($sum + $i))
i=$(($i + 1))
done
echo "the result of \"1+2+3+...+100\" is ==> $sum"
```
方法2:
```shell
s=0
i=0
# i的值只要不等于100就会一直循环
while test $i -ne 100
do
i=`expr $i + 1`
s=`expr $s + $i`
done
echo "the result of \"1+2+3+...+100\" is ==> $s"
```
编写一个shell1+2+3+...+100
以下是两种编写shell脚本求1+2+3+...+100的方法:
方法1:
```shell
sum=0
i=0
while ((i<=100))
do
sum=$(($sum + $i))
i=$(($i + 1))
done
echo "the result of \"1+2+3+...+100\" is ==> $sum"
```
方法2:
```shell
s=0
i=0
# i的值只要不等于100就会一直循环
while test $i -ne 100
do
i=`expr $i + 1`
s=`expr $s + $i`
done
echo "the result of \"1+2+3+...+100\" is ==> $s"
```