[英]Shell Function to Print factors of the first line argument
For a task I have to write a function that prints the number of numbers that are factors of 12 when provided with a sequence of numbers.对于一项任务,我必须编写一个 function,当提供一系列数字时,它会打印出 12 的因数。 My problem now is that my function keeps printing 0. What am I doing wrong?
我现在的问题是我的 function 一直打印 0。我做错了什么?
Below is my code:下面是我的代码:
#!/usr/bin/bash
#File: Num_Factor
#Write a function which prints factors of the first argument
function num_factor {
local sum=0
for element in $@; do
let factorcheck=$(( element % 2 ))
if [[ $factorcheck -eq 0 ]]; then
let sum=sum+1
fi
done
echo $sum
}
num_factor
The expected output am trying to achieve should be something similar to this:我试图实现的预期 output 应该类似于以下内容:
$num_factor 12 4 6 1 5
4
Thanks.谢谢。
Assumptions:假设:
bc
? awk
?)bc
? awk
?) Making a few tweaks to OP's current code:对 OP 的当前代码进行一些调整:
num_factor() {
local sum=0 first=$1 # initialize counter, grab first parameter
# shift # uncomment this line if the first parameter is *NOT* to be compared with itself
for element in "$@"; do
[[ "$element" -eq 0 ]] && continue # skip 'divide by 0' scenario
[[ $((first % element)) -eq 0 ]] && let sum=sum+1
done
echo $sum
}
Taking it for a test drive:拿它来试驾:
$ num_factor 12 4 6 1 5
4
$ num_factor 13
1
$ num_factor 13 2 3 5 7 9 11
1
$ num_factor -12 2 6 -3 5 1
5
$ num_factor 0 1 2 3 4 5 6
6 # based on OP's current logic; OP may want to reconsider how to address when 1st parameter == `0`
$ num_factor 720 2 3 4 5 6
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.