跳過到頁腳內容
.NET幫助

C# 數學(開發者的工作原理)

C# 是用來建立動態和擴展應用程式的熱門程式語言之一。 這種語言的一個優勢在於其內建函數的龐大函數庫,特別是數學函數。 在本教程中,我們將深入探討 C# 提供的各種數學函數,幫助您熟悉 Math 類,並瞭解如何輕鬆執行常見的數學方程。

入門指南

在 C# 中,Math 類是一個在 System 命名空間中可用的靜態類。 這個類包含大量的方法,旨在幫助開發人員執行數學運算,而無需從頭撰寫這些運算。

如何訪問 Math 類

要訪問 Math 類,您需要在公用類程式中包含 System 命名空間。 方法如下:

using System;

public class Program
{
    // Entry point of the program
    public static void Main()
    {
        // Your code goes here
    }
}
using System;

public class Program
{
    // Entry point of the program
    public static void Main()
    {
        // Your code goes here
    }
}
Imports System

Public Class Program
	' Entry point of the program
	Public Shared Sub Main()
		' Your code goes here
	End Sub
End Class
$vbLabelText   $csharpLabel

public static void Main 方法中,您可以透過參考 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
$vbLabelText   $csharpLabel

平方根: 若要找到指定數字的平方根,您可使用 Math.Sqrt() 函數。 這個函數計算平方根,並以如下範例的形式返回一個雙精度值:

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
$vbLabelText   $csharpLabel

數字舍入: 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
$vbLabelText   $csharpLabel

三角函數及雙曲線函數

除了基本的算術運算,C# 的 Math 類還提供一系列的三角函數和雙曲線函數。

正弦值: 要計算指定角度(以弧度為單位)的正弦值,使用 Math.Sin()

double angle = Math.PI / 2; // 90 degrees in radians
double sineValue = Math.Sin(angle);
Console.WriteLine(sineValue); // Output: 1
double angle = Math.PI / 2; // 90 degrees in radians
double sineValue = Math.Sin(angle);
Console.WriteLine(sineValue); // Output: 1
Dim angle As Double = Math.PI / 2 ' 90 degrees in radians
Dim sineValue As Double = Math.Sin(angle)
Console.WriteLine(sineValue) ' Output: 1
$vbLabelText   $csharpLabel

雙曲線函數: 這些函數類似於三角函數,但用於雙曲線方程。 一些例子包括 Math.Sinh()(雙曲正弦)、Math.Cosh()(雙曲餘弦)和 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)
$vbLabelText   $csharpLabel

高階數學函數

對於尋求更高級運算的人來說:

冪次方: Math.Pow() 函數接收兩個 double 型數字:一個底數和指數。 它返回該底數的指定次方。

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
$vbLabelText   $csharpLabel

對數: C# 提供了 Math.Log() 函數,該函數計算指定數字的自然對數(以 e 為底)。 此外,您可以使用 Math.Log(number, specified base) 指定基數。

double value = 10;
double naturalLog = Math.Log(value); // Natural logarithm base e
double logBase10 = Math.Log(value, 10); // Base 10 logarithm
double value = 10;
double naturalLog = Math.Log(value); // Natural logarithm base e
double logBase10 = Math.Log(value, 10); // Base 10 logarithm
Dim value As Double = 10
Dim naturalLog As Double = Math.Log(value) ' Natural logarithm base e
Dim logBase10 As Double = Math.Log(value, 10) ' Base 10 logarithm
$vbLabelText   $csharpLabel

C# 中的複數

儘管本教程主要涉及基本和中級函數,但值得注意的是 C# 支援複數。

創建複數: 使用 System.Numerics 命名空間中的 Complex 類。 它不是 Math 類的一部分,但對於涉及複數的數學運算至關重要。

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
$vbLabelText   $csharpLabel

Math 類中的轉換函數

開發人員常常需要在不同類型的數值之間進行轉換:

轉換為整數: 如果您有一個 double 並希望透過移除小數值將其轉換為整數,使用 Convert.ToInt32() 方法。

double value = 10.99;
int intValue = Convert.ToInt32(value);
Console.WriteLine(intValue); // Output: 11 (rounds 10.99 to the nearest integer)
double value = 10.99;
int intValue = Convert.ToInt32(value);
Console.WriteLine(intValue); // Output: 11 (rounds 10.99 to the nearest integer)
Dim value As Double = 10.99
Dim intValue As Integer = Convert.ToInt32(value)
Console.WriteLine(intValue) ' Output: 11 (rounds 10.99 to the nearest integer)
$vbLabelText   $csharpLabel

十進制到二進制: C# 沒有在 Math 類中的直接方法來實現這一點。 但是,您可以使用來自 System 命名空間的 Convert.ToString(value, 2) 函數。

int value = 42;
string binary = Convert.ToString(value, 2); // Converts 42 to binary
Console.WriteLine(binary); // Output: 101010
int value = 42;
string binary = Convert.ToString(value, 2); // Converts 42 to binary
Console.WriteLine(binary); // Output: 101010
Dim value As Integer = 42
Dim binary As String = Convert.ToString(value, 2) ' Converts 42 to binary
Console.WriteLine(binary) ' Output: 101010
$vbLabelText   $csharpLabel

數學函數的錯誤和例外處理

使用 Math 函數時,有時可能會遇到錯誤,例如除以零。 必須處理這些潛在的陷阱:

除以零: 使用條件語句在進行除法之前檢查除數。

double numerator = 10;
double denominator = 0;

if (denominator != 0)
{
    double result = numerator / denominator;
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Cannot divide by zero!");
}
double numerator = 10;
double denominator = 0;

if (denominator != 0)
{
    double result = numerator / denominator;
    Console.WriteLine(result);
}
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
	Console.WriteLine(result)
Else
	Console.WriteLine("Cannot divide by zero!")
End If
$vbLabelText   $csharpLabel

處理溢出: 當數學運算結果太大而超出其數據類型時,就會發生溢出。 使用檢查塊來捕獲此例外。

try
{
    checked
    {
        int result = checked(int.MaxValue + 1); // This will cause an overflow
    }
}
catch (OverflowException ex)
{
    Console.WriteLine("Overflow occurred: " + ex.Message);
}
try
{
    checked
    {
        int result = checked(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
'INSTANT VB TODO TASK: There is no VB equivalent to 'checked' in this context:
'ORIGINAL LINE: int result = checked(int.MaxValue + 1);
		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
$vbLabelText   $csharpLabel

介紹 Iron Suite:適用於 C# 開發者的強大套裝

當我們深入探討 C# 的功能時,值得注意的是,這種程式語言的生態系統已經發展得極具突破。 其中一個貢獻是 Iron Suite,這是一個為 C# 開發者量身定制的綜合工具包。 它提供了一組產品,可以強化您的應用程式,確保其堅固且功能豐富。

IronPDF

C# Math(開發者如何運作)圖 1 - IronPDF

是否曾感到需要在您的 C# 應用程式中處理 PDF? IronPDF 用於 C# 應用程式的 PDF 集成 是您的首選解決方案。 它極其簡單地創建、編輯甚至從 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
$vbLabelText   $csharpLabel

IronXL

C# Math(開發者如何運作)圖 2 - IronXL

數據處理是程式設計的一個重要方面,當涉及電子表格時,IronXL 用於 C# 中的 Excel 互通 已經為您準備好了。 無論您是在創建、閱讀還是編輯 Excel 文件,IronXL 都可以與 C# 無縫整合。 藉助 C# 的強大數學功能,您可以直接在應用程式內對 Excel 數據執行計算。

IronOCR

C# Math(開發者如何運作)圖 3 - IronOCR

光學字符識別(OCR)不再是一個未來的概念,而是透過 IronOCR 用於從圖像和 PDF 提取文本 的現實。 如果您有一個處理圖像或掃描文檔的應用程式並希望提取文本,特別是數據或數學公式,IronOCR 與 C# 的結合可以無縫地識別和轉換為可用的數據。

IronBarcode

C# Math(開發者如何運作)圖 4 - IronBarcode

在當今世界,條形碼在產品識別中扮演著不可或缺的角色。 利用 IronBarcode 用於 C# 中的生成和條形碼讀取,C# 開發者可以輕鬆地生成、讀取和處理條形碼。 如果您正在開發與庫存或銷售點系統相關的程式,條形碼與數學計算交織在一起,它尤其有用。

結論

C# Math(開發者如何運作)圖 5 - 許可證

C# 的技術領域廣袤且強大,有了像 Iron Suite 這樣的工具,您可以將應用程式提升到新的高度。 值得注意的是,Iron Suite 中的每個產品,不管是 IronPDF、IronXL、IronOCR 還是 IronBarcode,許可證均從 $799 開始。 此外,對於那些希望在投資前進行嘗試的人來說,每款產品均提供一個 Iron Suite 廣泛功能的 30 天免費試用,價格僅限兩款產品。 這樣的交易不僅提供了成本降低,而且還確保您擁有能應對多樣化開發需求的綜合工具包。

常見問題解答

如何使用 C# 中的 Math 類執行基本算術運算?

C# 中的 Math 類提供了方法,例如 Math.Abs() 用於計算絕對值,Math.Sqrt() 用於計算平方根,以及 Math.Round() 用於對數字進行四捨五入。這些方法簡化了基本的算術運算,無需撰寫複雜的算法。

C# 的 Math 類中有哪些高級數學函數可用?

對於高級數學運算,C# 的 Math 類提供了像 Math.Pow() 用於冪計算和 Math.Log() 用於對數運算的方法。這些功能允許開發人員高效處理複雜的計算。

如何處理 C# 中的除以零錯誤?

要在 C# 中處理除以零錯誤,使用條件語句進行檢查,以確認除數為零的情況,然後進行除法運算。或者,實施 try-catch 塊來管理由除法運算引起的任何異常。

如何將 PDF 功能整合到我的 C# 應用程序中?

IronPDF 使 C# 開發人員能夠無縫創建、修改和轉換內容到 PDF 文件。通過 IronPDF,您可以直接從 C# 應用程序中生成報告和以 PDF 格式顯示數學數據。

在 C# 中有哪些選擇可以用於操作 Excel 文件?

IronXL 允許 C# 開發人員以程序方式創建、讀取和編輯 Excel 文件。它與 C# 應用程序完美結合,可在 Excel 試算表中進行計算和數據操作。

如何使用 C# 從圖像中提取文本?

IronOCR 是一個強大的工具,用於在 C# 中從圖像中提取文本。它可以準確地識別和轉換來自掃描文件的文本和數據,增強需要光學字符識別的應用程序。

在 C# 中是否可以生成和讀取條形碼?

是的,IronBarcode 允許 C# 開發人員輕鬆生成和讀取各類型的條形碼。此功能在庫存管理或銷售點系統等需要條形碼掃描的應用程序中特別有用。

Iron Suite 為 C# 開發人員提供了哪些優勢?

Iron Suite 提供了一整套工具,包括 IronPDF、IronXL、IronOCR、IronBarcode 增強 C# 應用程序的功能。它提供 30 天免費試用,讓開發人員能夠有效地測試和整合這些功能。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。