For循环求助(新手学循环)

sh/bash/dash/ksh/zsh等Shell脚本
回复
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

For循环求助(新手学循环)

#1

帖子 LU开拓者 » 2012-03-02 16:00

#!/bin/bash
declare -i n=10
for((i=1;i<=$n;i++))
do

declare -i a=$n+$(n-1)

echo $a
done

echo "a="$a

运行结果:
./For.sh: 行 6: n-1: 未找到命令
./For.sh: 行 6: declare: 10+: 语法错误: 期待操作数 (错误符号是 "+")
a=


求大神指教 :em06
zcf115
帖子: 398
注册时间: 2009-06-28 10:06
系统: ubuntu12.04

Re: For循环求助(新手学循环)

#2

帖子 zcf115 » 2012-03-02 18:25

#!/bin/bash
declare -i n=10
for((i=1;i<=$n;i++))
do

declare -i a=$n+$(($n-1))

echo $a
done

echo "a="$a
Still Alive
zcf115
帖子: 398
注册时间: 2009-06-28 10:06
系统: ubuntu12.04

Re: For循环求助(新手学循环)

#3

帖子 zcf115 » 2012-03-02 18:26

declare -i a=$n+$(($n-1)) 注意这行。
Still Alive
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

Re: For循环求助(新手学循环)

#4

帖子 LU开拓者 » 2012-03-02 18:32

zcf115 写了:#!/bin/bash
declare -i n=10
for((i=1;i<=$n;i++))
do

declare -i a=$n+$(($n-1))

echo $a
done

echo "a="$a
我执行起来还是有问题额 :em20

19
19
19
19
19
19
19
19
19
19
a=19


我想循环加起来的。。。
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

Re: For循环求助(新手学循环)

#5

帖子 LU开拓者 » 2012-03-02 18:37

看下面这一段吧 还是全19....
#!/bin/bash
declare -i n=10
for((i=$n;i>=1;i--))
do
if [ i=10 ]
then
declare -i a=19
echo $a
else
declare -i m=$i-1
declare -i a=$i+$m+$a
echo $a
fi
done

echo "a="$a
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

Re: For循环求助(新手学循环)

#6

帖子 aerofox » 2012-03-02 19:39

n 一直没变,当然一直为19了。

代码: 全选

#!/bin/bash
n=10
a=0
for ((i=1; i<=n; i++))
do
    ((a += i ))
    echo $a
done

echo "a="$a
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

Re: For循环求助(新手学循环)

#7

帖子 LU开拓者 » 2012-03-05 9:52

:em38
((a += i ))这句不太懂额
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

Re: For循环求助(新手学循环)

#8

帖子 LU开拓者 » 2012-03-05 9:56

a=a+i?
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

Re: For循环求助(新手学循环)

#9

帖子 aerofox » 2012-03-05 12:57

是这个意思,跟C语言一样呀,应该很好懂的。
不知你要的是不是这个结果。
头像
LU开拓者
帖子: 59
注册时间: 2012-02-29 10:07

Re: For循环求助(新手学循环)

#10

帖子 LU开拓者 » 2012-03-05 13:33

明白了 :em11
回复