📜  用于查找数字总和的 Bash shell 脚本

📅  最后修改于: 2022-05-13 01:57:28.083000             🧑  作者: Mango

用于查找数字总和的 Bash shell 脚本

给定一个数 Num,求该数的位数之和。
例子:

Input : 
444
Output :
sum of digits of 444 is : 12

Input :
34
Output :
sum of digits of 34 is : 7

方法:

1. Divide the number into single digits
2. Find the sum of digits .
Bash
# !/bin/bash
 
# Program to find sum
# of digits
 
# Static input of the
# number
Num=123
g=$Num
 
# store the sum of
# digits
s=0
 
# use while loop to
# calculate the sum
# of all digits
while [ $Num -gt 0 ]
do
    # get Remainder
    k=$(( $Num % 10 ))
 
    # get next digit
    Num=$(( $Num / 10 ))
 
    # calculate sum of
    # digit 
    s=$(( $s + $k ))
done
echo  "sum of digits of $g is : $s"


输出:

sum of digits of 123 is : 6