暂无 |

赋值运算符

'='赋值运算符用于为任何变量赋值。它具有从左到右的结合性,即在操作符右侧给出的值被分配给左侧的变量,因此右侧的值必须在使用前声明或者应该是常量。
赋值运算符的一般格式是,

variable = value;

在许多情况下,赋值运算符可以与其他运算符结合使用以构建称为复合语句的简短版本的语句。例如,而不是a = a + 5,我们可以写一个+ = 5。

  • + =,用于向右操作数添加左操作数,然后将其分配给左侧的变量。
  • - =,用右操作数减去左操作数,然后将其分配给左侧的变量。
  • * =,用于将左操作数与右操作数相乘,然后将其分配给左侧的变量。
  • / =,用左操作数除以右操作数,然后将其分配给左侧的变量。
  • ^ =,用于将左操作数的功率提高到右操作数并将其分配给左侧的变量。
  • %=,用左操作数分配左操作数模数,然后将其分配给左侧的变量。
int a = 5;
a + = 5; // a = a + 5;
// Java program to illustrate
// assignment operators
public class operators 
{
    public static void main(String[] args) 
    {
        int a = 20, b = 10, c, d, e = 10, f = 4, g = 9;

        // simple assignment operator
        c = b;
        System.out.println("Value of c = " + c);

        // This following statement would throw an exception
        // as value of right operand must be initialised
        // before assignment, and the program would not
        // compile.
        // c = d;

        // instead of below statements,shorthand
        // assignment operators can be used to
        // provide same functionality.
        a = a + 1;
        b = b - 1;
        e = e * 2;
        f = f / 2;
        System.out.println("a,b,e,f = " + a + "," 
                           + b + "," + e + "," + f);
        a = a - 1;
        b = b + 1;
        e = e / 2;
        f = f * 2;

        // shorthand assignment operator
        a += 1;
        b -= 1;
        e *= 2;
        f /= 2;
        System.out.println("a,b,e,f (using shorthand operators)= " + 
                            a + "," + b + "," + e + "," + f);
    }
}

输出:

Value of c =10
a,b,e,f = 21,9,20,2
a,b,e,f (using shorthand operators)= 21,9,20,2

0

java教程
php教程
php+mysql教程
ThinkPHP教程
MySQL
C语言
css
javascript
Django教程

发表评论

    评价:
    验证码: 点击我更换图片
    最新评论