.NET 幫助

C# 數學(開發者如何使用)

Chipego
奇佩戈·卡林达
2023年12月12日
分享:

C# 是一種受歡迎的程式語言,用於構建動態且可擴展的應用程式。 這種語言的優勢之一在於其龐大的內建函式庫,特別是數學函數。 在本教程中,我們將深入探討 C# 提供的各種數學函數,幫助您熟悉 Math 類別,以及如何輕鬆進行常見的數學運算。

入門

在 C# 中,Math 類別System 命名空間 中的一個靜態類別。 此類別包含大量方法,旨在協助開發人員執行數學運算,無需從頭開始撰寫。

如何访问 Math 类

要使用 Math 類,您需要在您的公共類 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
$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
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
$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 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 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
$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: 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
$vbLabelText   $csharpLabel

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

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

在使用數學函數時,你可能偶爾會遇到錯誤,比如除以零。 要妥善處理這些潛在的陷阱:

被零除:在進行除法操作前,使用條件語句檢查除數。

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

處理溢位:當數學運算結果超出其資料類型的範圍時,就會發生溢位。 使用檢查區塊來捕捉此異常。

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

介紹 Iron Suite:為 C# 開發者打造的強大套件

當我們深入探討 C# 的功能時,值得注意的是環繞此程式語言的生態系統已經有了巨大的發展。 其中一項貢獻是 Iron Suite,它是專為 C# 開發人員量身打造的綜合工具包。 它提供一套產品,可以提升您的應用程序,確保它們穩健且功能豐富。

IronPDF

C# 數學(如何適用於開發人員)圖 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# 數學(開發者如何使用)圖 2 - IronXL

資料操作是程式設計的重要方面,而當涉及到試算表時,IronXL for Excel Interop in C# 可以滿足您的需求。 無論您是創建、讀取還是編輯 Excel 檔案,IronXL 都能輕鬆地與 C# 整合。 使用 C# 的數學函數,你可以在應用程式中直接對 Excel 數據進行計算。

IronOCR

C# 數學(對開發人員的運作方式)圖 3 - IronOCR

光學字符識別 (OCR) 已不再是未來的概念,而是將其變成現實,透過IronOCR 從圖像和 PDF 中提取文字。 如果您有處理圖像或掃描文件的應用程式,並希望提取文字,特別是數據或數學方程式的情況下,IronOCR 結合 C# 可以無縫地識別並將其轉換為可用數據。

IronBarcode

C# 數學(它對開發者的運作方式)圖 4 - IronBarcode

在當今世界,條碼在產品識別中起著不可或缺的作用。 使用IronBarcode 生成和讀取 C# 條碼,C# 開發人員可以輕鬆生成、讀取和處理條碼。 如果您正在開發庫存系統或銷售點系統,其中數學計算與條碼交織,這可能特別有用。

結論

C# 數學(開發人員如何使用)圖 5 - 授權

C# 的領域廣闊且強大,通過使用 Iron Suite 等工具,您可以將應用程式提升到新的高度。 值得注意的是,Iron Suite 中的每個產品,無論是 IronPDF、IronXL、IronOCR 或 IronBarcode,均從$749開始提供許可證。 此外,對於那些希望在投資前試用的人而言,每個產品都提供Iron Suite 豐富功能的 30 天免費試用,價格僅相當於兩個產品。 這樣的交易不僅能節省成本,還能確保您擁有一套全面的工具來滿足您多樣化的開發需求。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
字串生成器 C#(它對開發人員的運作方式)
下一個 >
C# 切換表示式 (適用於開發者的工作原理)