欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Dart 常用操作符 - 算术操作符

最编程 2024-10-15 08:52:59
...

These allow you to perform basic arithmetic calculations on numeric data. Dart supports all the standard arithmetic operators, including addition (+), subtraction (-), multiplication (*), division (/), and modulo (remainder) (%).

它们允许您对数字数据执行基本的算术计算。Dart支持所有标准算术运算符,包括加法(+)、减法(-)、乘法(*)、除法(/)和取模(余数)(%)。

Here are some examples of using arithmetic operators in Dart:

下面是一些在Dart中使用算术运算符的例子:

Addition (+): Adds two numbers together

加法(+):将两个数字相加

int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
print(“Sum: $sum”); // Output: Sum: 30

Subtraction (-): Subtracts the second number from the first number.

减法(-):用第一个数减去第二个数。

int num1 = 25;
int num2 = 15;
int difference = num1 - num2;
print(“Difference: $difference”); // Output: Difference: 10

Multiplication (*): Multiplies two numbers together.

乘法(*):将两个数字相乘。

int num1 = 5;
int num2 = 6;
int product = num1 * num2;
print(“Product: $product”); // Output: Product: 30

Division (/): Divides the first number by the second number. Note that if both numbers are integers, the result will also be an integer.

除法(/):用第一个数除以第二个数。注意,如果两个数字都是整数,结果也将是整数。

int num1 = 20;
int num2 = 4;
double quotient = num1 / num2;
print(“Quotient: $quotient”); // Output: Quotient: 5.0

Modulo (%): Returns the remainder of the division of the first number by the second number. One of the popular uses of this operator is to identify even or odd numbers in a set of numbers.

模数(%):返回第一个数字除以第二个数字的余数。这个运算符的一个常用用途是在一组数字中识别偶数或奇数。

int num1 = 25;
int num2 = 7;
int remainder = num1 % num2;
print(“Remainder: $remainder”); // Output: Remaind

These arithmetic operators can be used with different numeric data types, such as integers and doubles, allowing you to perform various calculations in your Dart programs. Remember to use parentheses when necessary to control the order of operations and ensure the correct result in complex calculations.

这些算术运算符可用于不同的数字数据类型,例如整数和双精度,从而允许您在Dart程序中执行各种计算。在复杂的计算中,为了控制运算顺序并确保正确的结果,必要时要记住使用括号。

示例代码:

void main() {
  int a = 3;
  int b = 33;
  int c;

  // 加法
  c = a + b;
  print("$a + $b = $c");

  // 减法
  c = a - b;
  print("$a - $b = $c");

  // 乘法
  c = a * b;
  print("$a x $b = $c");

  // 除法
  // 结果是 double 类型, 要转换为 int 类型
  double c2 = a / b;
  print("$a / $b = $c2");

  // 取余
  c = a % b;
  print("$a % $b = $c");
}

输出:

3 + 33 = 36
3 - 33 = -30
3 x 33 = 99
3 / 33 = 0.09090909090909091
3 % 33 = 3