.NET 幫助

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

發佈 2023年12月12日
分享:

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

入門

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

如何存取 Math 類別

要存取 Math 類別,您需要在您的公共類別程序中包括 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 類中的任何函數。** 使用输出参数,该参数也可以是浮点数。

基本數學函數

讓我們來看看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 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 類還提供了一系列的三角函數及雙曲線函數

正弦值: 要找出指定角度的正弦值 (以弧度),使用 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.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)
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#中的複數

雖然本教程主要處理基本和中級函數,但值得注意的是,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
VB   C#

數學類別中的轉換函數

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

轉換為整數: 如果你有一個 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
VB   C#

十進制到二進制: C# 在 Math 類中沒有直接的方法。但你可以使用 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#

處理溢出: 當數學運算導致的值對數據類型來說過大時,會發生溢出。使用checked區塊來捕捉這個例外。

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#

介紹 Iron Suite 一款強大的 C# 開發者套件

當我們深入了解 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.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >