我试着把所有奇数的乘积都求到n,但输出总是0。
read -p "Enter a number: " n
prod=0
for((k=1; k<=n; k++))
do
if [ k%1==0 ]
then
prod=$((prod*=k))
fi
done
echo "Product of odd counting numbers until $n is $prod"发布于 2021-02-17 01:34:39
对于这个任务,模运算是多余的。只需使用增量为2的C风格的for循环:
#!/bin/bash
read -p "Enter a number: " n
prod=1
for ((k = 3; k <= n; k += 2)); do ((prod *= k)); done
echo "Product of odd counting numbers until $n is $prod"请注意,产品很容易溢出。例如,在64位系统上,当n等于或大于35时。如果您想要获得更大的n的正确结果,您可能需要使用bc实用程序:
#!/bin/bash
read -p "Enter a number: " n
prod=1
for ((k = 3; k <= n; k += 2)); do prod+="*$k"; done
printf "Product of odd counting numbers until %d is " "$n"
bc <<< "$prod"请注意,在此上下文中,prod+="*$k"是字符串连接,而不是算术操作。
发布于 2021-02-16 22:10:01
任何算术表达式都需要在$((..))中因此:
read -p "Enter a number: " n
prod=0
for((k=1; k<=n; k++))
do
if [[ "$((k%1))" == "0" ]]
then
prod=$((prod*=k))
fi
done
echo "Product of odd counting numbers until $n is $prod"发布于 2021-02-16 22:14:09
四个问题:
[ k%1==0 ]表示“字符串k%1==0是否是非空的?”它一直都是,所以这将永远是正确的。- You need blanks around the operator, and `==` is only allowed in Bash, but not Posix compliant.
- `k%1` is just a string; you need an arithmetic context to do math.总而言之,这将是
如果$((k%1)) =0;则
但是可以在Bash中替换为
if ((k%1 == 0));则
如果((k%2 == 1));则
,可以缩写为
如果((k%2);则
因为((...))中的非零结果是真的
prod=$((prod*=k))有一个冗余的赋值:您可以使用((prod *= k))
在它自己的上
prod=1开始,否则它将始终保持为0合并,修复所有ShellCheck投诉:
#!/usr/bin/env bash
read -rp "Enter a number: " n
prod=1
for ((k = 1; k <= n; ++k)); do
((k % 2)) && ((prod *= k))
done
echo "Product of odd counting numbers until $n is $prod"https://stackoverflow.com/questions/66225571
复制相似问题