这两个表达式有什么区别

这两个表达式有什么区别

我是新手。好吧,我有点不明白以下两者的区别:

let a=$a+$b
let i=$i+1 

和:

a+=$b
i=$(($i + 1))

肯定是有区别的,因为第二个表达式毁了我的脚本,给出了一个垃圾值。

这是我的脚本:

问题是[脚本需要让用户能够输入一些分数,直到用户给出 q(作为退出)或负值,最后我们需要计算给定分数的中间值]

这个脚本可以运行,但是如果你改变let moyenne=$moyenne+$note并且let i=$i+1使用moyenne+=$note并且i=$(($i + 1)) 它将给出一个垃圾值moyenne(中间值)。

#!/bin/bash

note=0
meyenne=0
i=0

until [ "$note" -lt 0 ]; do
  read -p "Entrer la note (appuyez sur q pour quitter): " note
  if [ "$note" = "q" ]; then
    note=-4
    echo "Exit"
  elif [ "$note" -ge 16 ]; then
    echo "Tres Bien"
  elif [ "$note" -ge 14 ]; then
    echo "Bien"
  elif [ "$note" -ge 12 ]; then
    echo "Assez bien"
  elif [ "$note" -ge 10 ]; then
    echo "Moyen"
  elif [ "$note" -ge 0 ]; then
    echo "Insuffi"
  else
    echo "Exit"
  fi
  if [ "$note" -ge 0 ]; then
    let moyenne=$moyenne+$note
    let i=$i+1
  fi
done
moyenne=$(($moyenne / $i))
echo "la moyenne est $moyenne de $i notes"

答案1

相关章节man bash

   In  the context where an assignment statement is assigning a value to a
   shell variable or array index, the += operator can be used to append to
   or  add  to  the variable's previous value.  This includes arguments to
   builtin commands such as  declare  that  accept  assignment  statements
   (declaration commands).  When += is applied to a variable for which the
   integer attribute has been set, value is evaluated as an arithmetic ex‐
   pression and added to the variable's current value, which is also eval‐
   uated.  When += is applied to an array variable using compound  assign‐
   ment  (see  Arrays  below), the variable's value is not unset (as it is
   when using =), and new values are appended to the  array  beginning  at
   one  greater  than  the  array's  maximum index (for indexed arrays) or
   added as additional key-value pairs in an associative array.  When  ap‐
   plied  to  a  string-valued variable, value is expanded and appended to
   the variable's value.

由于您尚未设置 的整数属性a,因此a+=$b将执行字符串连接而不是算术加法:

$ a=1; b=2; a+=$b; echo "$a"
12

然而

$ unset a b
$ declare -i a=1; b=2; a+=$b; echo "$a"
3

或者,你可以使用以下方式强制进行算术评估(( ... ))

$ unset a b
$ a=1; b=2; ((a+=$b)); echo "$a"
3

(请注意,这((a+=b))也有效;$在算术上下文中不需要取消引用变量)。

相关内容