• linux中 for语句和while语句计算1100的和


    1、for语句

    [root@centos7 test2]# cat test.sh
    #!/bin/bash
    sum=0
    for i in `seq $1`
    do
    let sum+=$i
    done
    echo "the sum of 1-$1 is: $sum"
    [root@centos7 test2]# bash test.sh 100
    the sum of 1-100 is: 5050
    [root@centos7 test2]# bash test.sh 5
    the sum of 1-5 is: 15
    [root@centos7 test2]# cat test.sh
    #!/bin/bash
    sum=0
    read -p "please input an integer: " num
    if [[ $num =~ [^0-9] ]]; then
    echo "input error."
    exit 10
    elif [ $num -eq 0 ]; then
    echo "input error."
    exit 20
    else
    for i in `seq 1 $num`; do
    sum=$[$sum+$i]
    done
    echo $sum
    fi
    unset sum
    [root@centos7 test2]# bash test.sh
    please input an integer: abcd
    input error.
    [root@centos7 test2]# bash test.sh
    please input an integer: 0
    input error.
    [root@centos7 test2]# bash test.sh
    please input an integer: -3
    input error.
    [root@centos7 test2]# bash test.sh
    please input an integer: 100
    5050

    1-100的和

    [root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do let sum+=$i; done
    [root@centos7 test2]# echo $sum
    5050

    1-100中偶数的和

    [root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do [[ $[i%2] -eq 0 ]] && sum=$[$sum+$i]; done
    [root@centos7 test2]# echo $sum
    2550

    1-100中奇数的和

    [root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do [[ $[i%2] -eq 1 ]] && let sum+=$i; done
    [root@centos7 test2]# echo $sum
    2500

    2、while语句

    [root@centos7 test2]# cat test.sh
    #!/bin/bash
    sum=0
    a=1
    while [ $a -le $1 ]
    do
    let sum+=$a
    let a++
    done
    echo "the sum of 1-$1 is: $sum"
    [root@centos7 test2]# bash test.sh 100
    the sum of 1-100 is: 5050
    [root@centos7 test2]# bash test.sh 3
    the sum of 1-3 is: 6

    1-100内所有奇数的和

    [root@centos7 test2]# cat test.sh
    #!/bin/bash
    i=1
    sum=0
    while [ $i -le 100 ]; do
    if [ $[i%2] -ne 0 ]; then
    let sum+=$i
    let i++
    else
    let i++
    fi
    done
    echo $sum
    [root@centos7 test2]# bash test.sh
    2500

    1-100内所有偶数的和

    [root@centos7 test2]# cat test.sh
    #!/bin/bash
    i=1
    sum=0
    while [ $i -le 100 ]; do
    if [ $[i%2] -eq 0 ]; then
    sum=$[$sum+$i]
    let i++
    else
    let i++
    fi
    done
    echo $sum
    unset sum
    [root@centos7 test2]# bash test.sh
    2550
  • 相关阅读:
    一张图了解.Net Core和.NetFx和.Net Standard和Xamarin关系
    .NETCore Docker实现容器化与私有镜像仓库管理
    .netcore consul实现服务注册与发现-集群部署
    .netcore consul实现服务注册与发现-单节点部署
    路径显示不下时,中间显示省略号
    CAD2015 C#二次开发 字体变形
    C# 加载并显示菜单
    作为公共组软件工程师如何工作
    面试北京XX科技总结
    面试北京XX数通总结
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14689109.html
Copyright © 2020-2023  润新知