Skip to content
On this page

数学运算符

执行基本的数学运算

编写代码以用整数执行加法、减法、乘法和除法运算

csharp
int sum = 7 + 5;
int difference = 7 - 5;
int product = 7 * 5;
int quotient = 7 / 5;

Console.WriteLine("Sum: " + sum);
Console.WriteLine("Difference: " + difference);
Console.WriteLine("Product: " + product);
Console.WriteLine("Quotient: " + quotient);

// Sum: 12
// Difference: 2
// Product: 35
// Quotient: 1

正如你所见:

  • + 是加法运算符
  • - 是减法运算符
  • * 是乘法运算符
  • / 是除法运算符

然而,除法示例的结果商可能不是你所期望的。小数后面的值从 quotient 中截断,因为它被定义为 int,并且 int 不能包含小数后面的值。

使用文本小数数据添加代码以执行除法

要查看除法是否正确有效,我们需要使用支持小数点后的小数位的数据类型,如 decimal

csharp
decimal decimalQuotient = 7.0m / 5;
Console.WriteLine("Decimal quotient: " + decimalQuotient);

// Decimal quotient: 1.4

为了使其正常运作,商(赋值运算符的左边)必须是类型 decimal 以及被除数或除数必须为类型 decimal(或两者都为该类型)。

以下是同样适用的两个其他示例:

csharp
decimal decimalQuotient = 7 / 5.0m;
decimal decimalQuotient = 7.0m / 5.0m;

但是,以下代码行会无效(或者会给出不准确的结果):

csharp
int decimalQuotient = 7 / 5.0m;
int decimalQuotient = 7.0m / 5;
int decimalQuotient = 7.0m / 5.0m;
decimal decimalQuotient = 7 / 5;

使用文本小数数据添加代码以执行除法

如果不使用文本值会怎么样?换句话说,如果需要将类型 int 的两个变量相除,但不希望结果被截断,该怎么办?在这种情况下,必须执行从 intdecimal 的数据类型强制转换。强制转换是一种数据转换类型,指示编译器临时将值视为不同的数据类型。

要将 int 强制转换为 decimal,请在值之前添加强制转换运算符。可以使用在值前面加括号括起来的数据类型名称来强制转换该数据类型。在本示例中,我们会将 (decimal) 添加到变量 firstsecond 之前。

csharp
int first = 7;
int second = 5;
decimal quotient = (decimal)first / (decimal)second;
Console.WriteLine(quotient);

// 1.4

备注

对于括号运算符,我们看到了三种用法或重载:方法调用、运算顺序和强制转换。

编写代码以确定整数相除后的余数

余数运算符 % 指示 int 相除后的余数。你真正从此运算符了解到的是一个数字是否可被另一个数字整除。当遍历数百条或数千条数据记录,并想要在每 100 条数据记录经过处理后向最终用户提供反馈时,这非常有用。

csharp
Console.WriteLine("Modulus of 200 / 5 : " + (200 % 5));
Console.WriteLine("Modulus of 7 / 5 : " + (7 % 5));

// Modulus of 200 / 5 : 0
// Modulus of 7 / 5 : 2

当模数为 0 时,表示被除数可以整除除数。

运算顺序

正如在上一个练习中了解到的,可以使用 () 符号作为运算符运算的顺序。但是,这不是确定运算顺序的唯一方法。

在数学中,PEMDAS 是一个首字母缩略词,有助于学生记住执行多个运算的顺序。此顺序为:

  1. 圆括号 (P)(括号内的内容首先执行)
  2. 指数 (E)
  3. 乘法 (M) 和除法 (D)(从左至右)
  4. 加法 (A) 和减法 (S)(从左至右)

C# 遵循与 PEMDAS 相同的顺序,但指数除外。虽然在 C# 中没有指数运算符,但可以使用 System.Math.Pow() 方法,此方法可从 .NET 类库中获得。 使用 C# 从 .NET 类库调用方法模块将使用此方法和其他方法。

编写代码练习 C# 的运算顺序

csharp
int value1 = 3 + 4 * 5;
int value2 = (3 + 4) * 5;
Console.WriteLine(value1);
Console.WriteLine(value2);

// 23
// 35

回顾

  • 使用如 +-*/ 的运算符来执行基本数学运算。
  • 两个 int 值相除,得到小数点后的任意值被截断的结果。要保留小数点后面的值,需要先将除数或被除数(或两者)由 int 强制转换为浮点数,如 decimal,然后为了避免截断,商必须是相同的浮点类型。
  • 执行强制转换操作,将值暂时视为不同的数据类型。
  • 使用 % 运算符捕获相除后的余数。
  • 操作顺序将遵循首字母缩略词 PEMDAS 的规则。