.NET 帮助

C# 数学(它对开发人员的工作原理)

发布 2023年十二月12日
分享:

C# 是构建动态和可扩展应用程序的流行编程语言之一。该语言的优势之一在于其庞大的内置函数库,尤其是数学函数。在本教程中,我们将深入探讨 C# 提供的各种数学函数,帮助您熟悉 数学课 以及如何轻松执行常见的数学公式。

开始

在 C# 中,数学类系统命名空间中的一个静态类。该类包含大量方法,旨在帮助开发人员执行数学运算,而无需从头开始编写。

如何进入数学课堂

要访问数学类,需要在公有类 Program 中包含 System 命名空间。具体方法如下

using System;
public class Program
{
//public static void Main method
    public static void Main()
    {
        // Your code goes here
    }
}
using System;
public class Program
{
//public static void Main method
    public static void Main()
    {
        // Your code goes here
    }
}
Imports System
Public Class Program
'public static void Main method
	Public Shared Sub Main()
		' Your code goes here
	End Sub
End Class
VB   C#

public static void main方法中,您可以通过引用Math.Math.Math来调用数学类中的任何函数。** 并使用输出参数,该参数也可以是浮点数。

基本数学函数

让我们来看看 C# 提供的一些基本数学函数

绝对值: 指定数字的绝对值是不带符号的数值。函数 Math.Abs() 输入一个数字并返回绝对值。

double val = -10.5;
double absValue = Math.Abs(val); //function returns absolute value
Console.WriteLine(absValue); // Output: 10.5
double val = -10.5;
double absValue = Math.Abs(val); //function returns absolute value
Console.WriteLine(absValue); // Output: 10.5
Dim val As Double = -10.5
Dim absValue As Double = Math.Abs(val) 'function returns absolute value
Console.WriteLine(absValue) ' Output: 10.5
VB   C#

平方根: 若要求出指定数字的平方根,可使用 Math.Sqrt() 函数。如下例所示,该函数计算平方根并返回一个 double 值。

double value = 16;
double sqrtValue = Math.Sqrt(value);
Console.WriteLine(sqrtValue); // Output: 4
double value = 16;
double sqrtValue = Math.Sqrt(value);
Console.WriteLine(sqrtValue); // Output: 4
Dim value As Double = 16
Dim sqrtValue As Double = Math.Sqrt(value)
Console.WriteLine(sqrtValue) ' Output: 4
VB   C#

对数字四舍五入: C# 提供了多个函数,可将数字四舍五入到最接近的整数或指定的小数位数。Math.Round() 函数将浮点数值舍入到最接近的整数或积分部分。

double value = 10.75;
double roundedValue = Math.Round(value); // rounds to the nearest whole number
Console.WriteLine(roundedValue); // Output: 11
double value = 10.75;
double roundedValue = Math.Round(value); // rounds to the nearest whole number
Console.WriteLine(roundedValue); // Output: 11
Dim value As Double = 10.75
Dim roundedValue As Double = Math.Round(value) ' rounds to the nearest whole number
Console.WriteLine(roundedValue) ' Output: 11
VB   C#

三角函数和双曲线函数

除了基本算术运算外,C# 中的数学类还提供了一系列三角函数和双曲函数

正弦值: 求指定角度的正弦值 (弧度), 使用 Math.Sin().

double angle = Math.PI / 2; // 90 degrees
double sineValue = Math.Sin(angle);
Console.WriteLine(sineValue); // Output: 1
double angle = Math.PI / 2; // 90 degrees
double sineValue = Math.Sin(angle);
Console.WriteLine(sineValue); // Output: 1
Dim angle As Double = Math.PI / 2 ' 90 degrees
Dim sineValue As Double = Math.Sin(angle)
Console.WriteLine(sineValue) ' Output: 1
VB   C#

双曲函数: 这些函数与三角函数类似,但用于双曲方程。一些例子包括 Math.Sinh() (双曲正弦),数学.科什() (双曲余弦)和 Math.Tanh() (双曲正切).

double value = 1;
double hyperbolicSine = Math.Sinh(value);
double hyperbolicCosine = Math.Cosh(value);
double hyperbolicTangent = Math.Tanh(value);
double value = 1;
double hyperbolicSine = Math.Sinh(value);
double hyperbolicCosine = Math.Cosh(value);
double hyperbolicTangent = Math.Tanh(value);
Dim value As Double = 1
Dim hyperbolicSine As Double = Math.Sinh(value)
Dim hyperbolicCosine As Double = Math.Cosh(value)
Dim hyperbolicTangent As Double = Math.Tanh(value)
VB   C#

高级数学函数

适用于寻求更高级运算的用户:

幂: Math.Pow() 函数接收两个整数:基数和指数。它返回基数乘以指定幂的结果。

double baseNum = 2;
double exponent = 3;
double result = Math.Pow(baseNum, exponent);
Console.WriteLine(result); // Output: 8
double baseNum = 2;
double exponent = 3;
double result = Math.Pow(baseNum, exponent);
Console.WriteLine(result); // Output: 8
Dim baseNum As Double = 2
Dim exponent As Double = 3
Dim result As Double = Math.Pow(baseNum, exponent)
Console.WriteLine(result) ' Output: 8
VB   C#

对数: C# 提供Math.Log() 函数,计算自然对数 (基 e) 的基数。此外,您还可以使用 Math.Log 指定基数。(数,指定基数).

double value = 10;
double naturalLog = Math.Log(value); // Natural logarithmic base
double logBase10 = Math.Log(value, 10); // Base 10 logarithm
double value = 10;
double naturalLog = Math.Log(value); // Natural logarithmic base
double logBase10 = Math.Log(value, 10); // Base 10 logarithm
Dim value As Double = 10
Dim naturalLog As Double = Math.Log(value) ' Natural logarithmic base
Dim logBase10 As Double = Math.Log(value, 10) ' Base 10 logarithm
VB   C#

C&num 中的复数;

虽然本教程主要涉及基本和中级函数,但值得注意的是,C# 提供了对复数的支持

创建复数: 使用System.Numerics命名空间中的Complex类。它不是数学类的一部分,但对涉及复数的数学运算至关重要。

using System.Numerics;
Complex complexNumber = new Complex(2, 3); // Represents 2 + 3i
using System.Numerics;
Complex complexNumber = new Complex(2, 3); // Represents 2 + 3i
Imports System.Numerics
Private complexNumber As New Complex(2, 3) ' Represents 2 + 3i
VB   C#

数学课上的转换函数

开发人员经常需要在不同类型的数值之间进行转换:

转换为整数: 如果您有一个二进制数,并希望通过删除其小数点值将其转换为整数,请使用 Convert.ToInt32() 方法。

double value = 10.99;
int intValue = Convert.ToInt32(value);
Console.WriteLine(intValue); // Output: 10
double value = 10.99;
int intValue = Convert.ToInt32(value);
Console.WriteLine(intValue); // Output: 10
Dim value As Double = 10.99
Dim intValue As Integer = Convert.ToInt32(value)
Console.WriteLine(intValue) ' Output: 10
VB   C#

十进制转二进制: C# 数学类中没有直接的方法。不过,您可以使用Convert.ToString(值,2) 来自 System 命名空间的函数。

数学函数的错误和异常处理

使用数学函数时,有时可能会遇到错误,例如除数为零。处理这些潜在的错误至关重要:

除数为零: 使用条件语句检查除数,然后再进行除法运算。

double numerator = 10;
double denominator = 0;
if(denominator != 0)
{
    double result = numerator / denominator;
}
else
{
    Console.WriteLine("Cannot divide by zero!");
}
double numerator = 10;
double denominator = 0;
if(denominator != 0)
{
    double result = numerator / denominator;
}
else
{
    Console.WriteLine("Cannot divide by zero!");
}
Dim numerator As Double = 10
Dim denominator As Double = 0
If denominator <> 0 Then
	Dim result As Double = numerator / denominator
Else
	Console.WriteLine("Cannot divide by zero!")
End If
VB   C#

溢出处理: 当数学运算产生的值对其数据类型而言过大时,就会发生溢出。使用校验块捕捉这种异常。

try
{
    checked
    {
        int result = int.MaxValue + 1; // This will cause an overflow
    }
}
catch(OverflowException ex)
{
    Console.WriteLine("Overflow occurred: " + ex.Message);
}
try
{
    checked
    {
        int result = int.MaxValue + 1; // This will cause an overflow
    }
}
catch(OverflowException ex)
{
    Console.WriteLine("Overflow occurred: " + ex.Message);
}
Try
'INSTANT VB TODO TASK: There is no equivalent to a 'checked' block in VB:
'	checked
		Dim result As Integer = Integer.MaxValue + 1 ' This will cause an overflow
'INSTANT VB TODO TASK: End of the original C# 'checked' block.
Catch ex As OverflowException
	Console.WriteLine("Overflow occurred: " & ex.Message)
End Try
VB   C#

为 C&num 开发人员提供的功能强大的套件

当我们深入研究 C# 的功能时,值得注意的是围绕这种编程语言的生态系统已经发生了巨大的变化。Iron Suite 就是其中之一,它是专为 C# 开发人员量身定制的综合工具包。它提供了一系列产品,可以为您的应用程序增添动力,确保其稳健且功能丰富。

IronPDF

C# 数学(如何为开发人员工作)图 1 - IronPDF

是否觉得有必要在 C# 应用程序中处理 PDF? IronPDF 是您的首选解决方案。它使 PDF 文件的创建、编辑甚至内容提取变得异常简单。如果将它与 C# 的数学功能相结合,就可以生成报告、图表和其他数学可视化内容,并将它们无缝嵌入到 PDF 文档中。

IronPDF 的一个突出功能是它的 HTML 转 PDF 功能,并保持所有布局和样式完好无损。它能从网页内容生成 PDF,适用于报告、发票和文档。HTML 文件、URL 和 HTML 字符串都可以毫不费力地转换为 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

IronXL

C# 数学(如何为开发人员工作) 图 2 - IronXL

数据处理是编程的一个重要方面,电子表格也是如此、 IronXL 为您提供支持。无论您是创建、读取还是编辑 Excel 文件,IronXL 都能毫不费力地与 C# 集成。借助 C# 数学函数的强大功能,您可以直接在应用程序中对 Excel 数据进行计算。

IronOCR

C# 数学(如何为开发人员工作) 图 3 - IronOCR

光学字符识别 (光学字符识别) 不再是未来的概念,而是现实,因为 IronOCR.如果您有一个处理图像或扫描文件的应用程序,并希望提取文本,特别是数字数据或数学公式,那么 IronOCR 与 C# 结合后就能无缝识别并将其转换为可用数据。

IronBarcode

C# 数学(如何为开发人员工作) 图 4 - IronBarcode

在当今世界,条形码在产品识别中发挥着不可或缺的作用。随着 IronBarcode条形码技术可以让 C# 开发人员轻松生成、读取和处理条形码。如果您正在开发数学计算与条形码相互交织的库存或销售点系统,它将特别有用。

结论

C# 数学(如何为开发人员工作) 图 5 - 许可证

C# 的应用领域广阔而强大,借助 Iron Suite 等工具,您可以将自己的应用程序提升到新的高度。值得注意的是,Iron Suite 中的每个产品,无论是 IronPDF、IronXL、IronOCR 还是 IronBarcode,都有从 $749 开始的许可证。此外,对于那些希望在投资前试用的用户,每个产品都提供了 30 天免费试用 只需两种产品的价格。这样的优惠不仅能节省成本,还能确保您拥有一套全面的工具包,满足您的各种开发需求。

< 前一页
适用于开发人员的字符串生成器 C#(工作原理)
下一步 >
C# 切换表达式(它是如何为开发人员工作的)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >