让我们深入了解 C# 中的各种运算符,包括算术、赋值、比较、逻辑运算符,以及 Math 类的应用。
C# 中的算术运算符用于执行基本的数学运算,如加法、减法、乘法和除法等。
int a = 10;
int b = 3;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
Console.WriteLine("Sum: " + sum);
Console.WriteLine("Difference: " + difference);
Console.WriteLine("Product: " + product);
Console.WriteLine("Quotient: " + quotient);
Console.WriteLine("Remainder: " + remainder);
赋值运算符用于将值赋给变量。
int x = 10;
int y = 5;
x += y; // 相当于 x = x + y;
Console.WriteLine("x: " + x);
比较运算符用于比较两个值,并返回一个布尔值。
int p = 10;
int q = 5;
bool isEqual = (p == q);
bool isNotEqual = (p != q);
bool isGreater = (p > q);
bool isLess = (p < q);
bool isGreaterOrEqual = (p >= q);
bool isLessOrEqual = (p <= q);
Console.WriteLine("isEqual: " + isEqual);
Console.WriteLine("isNotEqual: " + isNotEqual);
Console.WriteLine("isGreater: " + isGreater);
Console.WriteLine("isLess: " + isLess);
Console.WriteLine("isGreaterOrEqual: " + isGreaterOrEqual);
Console.WriteLine("isLessOrEqual: " + isLessOrEqual);
逻辑运算符用于在布尔表达式之间执行逻辑运算。
bool condition1 = true;
bool condition2 = false;
bool andResult = condition1 && condition2;
bool orResult = condition1 || condition2;
bool notResult = !condition1;
Console.WriteLine("andResult: " + andResult);
Console.WriteLine("orResult: " + orResult);
Console.WriteLine("notResult: " + notResult);
Math
类提供了许多用于执行常见数学运算的静态方法,如绝对值、三角函数、指数运算等。
double number = -5.5;
double absoluteValue = Math.Abs(number);
double sineValue = Math.Sin(number);
double exponentValue = Math.Exp(number);
Console.WriteLine("Absolute value: " + absoluteValue);
Console.WriteLine("Sine value: " + sineValue);
Console.WriteLine("Exponent value: " + exponentValue);
以上是关于 C# 运算符详解的内容。熟悉并理解这些运算符是编写和理解 C# 程序的重要基础。
原文链接:codingdict.net