跳過到頁腳內容
.NET幫助

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

C# 是建立動態和可擴充應用程式的常用程式語言之一。 此語言的優勢之一在於其大量的內建函式庫,尤其是數學函式。 在本教程中,我們將深入探討 C# 所提供的各種數學函數,協助您熟悉 Math class 以及如何輕鬆執行常見的數學方程式。

開始

在 C# 中,Math 類System 命名空間中的靜態類。 本類型包含大量方法,旨在幫助開發人員執行數學運算,而無需從頭寫起。

如何存取數學類

若要存取 Math 類,您需要在公有類別 Program 中包含 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 值,如以下範例所示:

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

進階數學函數

適合尋求更進階操作的人士:

Power: 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
$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 類。 這不是數學課的一部分,但對於涉及複數的數學運算來說是不可或缺的。

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

數學類中的轉換函數

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

轉換為整數:如果您有一個 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

使用數學函數處理錯誤和異常。

在使用數學函數時,有時可能會遇到錯誤,例如除數為零。 處理這些潛在的陷阱是非常重要的:

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

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# 數學運算(開發者如何理解)圖 1 - IronPDF

是否曾覺得需要在您的 C# 應用程式中使用 PDF? IronPDF for PDF Integration in C# Applications 是您的最佳解決方案。 它使 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 (How It Works For Developers) 圖 2 - IronXL

資料處理是程式設計的重要一環,當談到試算表時,IronXL for Excel Interop in C# 可以幫您解決問題。 無論您是建立、閱讀或編輯 Excel 檔案,IronXL.Excel 都能毫不費力地與 C# 整合。 借助 C# 數學函數的強大功能,您可以直接在應用程式中對 Excel 資料執行計算。

IronOCR。

C# Math (How It Works For Developers) 圖 3 - IronOCR

有了 IronOCR 從影像和 PDF 擷取文字的功能,光學字元識別 (OCR) 不再是未來的概念,而是現實。 如果您有處理影像或掃描文件的應用程式,並希望擷取文字,尤其是數值資料或數學方程式,IronOCR 結合 C# 就能無縫辨識並翻譯成可用的資料。

IronBarcode。

C# Math (How It Works For Developers) 圖 4 - IronBarcode

在現今世界,Barcode 在產品識別中扮演著不可或缺的角色。 透過 IronBarcode for Generating and Reading Barcodes in C#,C# 開發人員可以輕鬆地產生、讀取及處理條碼。 如果您正在開發數學計算與 BarCode 互相交織的庫存或銷售點系統,它可能會特別有用。

結論

C# Math (How It Works For Developers) 圖 5 - 授權

C# 的領域廣闊而強大,有了 Iron Suite 之類的工具,您可以將應用程式提升到新的高度。 值得注意的是,Iron Suite 中的每個產品,無論是 IronPDF、IronXL、IronOCR 或 IronBarcode,其許可證均以 $999 開頭。 此外,對於想要在投資前先試用的人,每項產品都提供 30天免費試用 Iron Suite 的豐富功能,價格僅為兩項產品的價格。 這樣的交易不僅能節省成本,還能確保您擁有全面的工具包,滿足您多樣化的開發需求。

常見問題解答

如何使用 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 天免費試用,讓開發人員能夠有效地測試和整合這些功能。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我