.NET ヘルプ

C# 数学(開発者向けの使い方)

C#は、動的でスケーラブルなアプリケーションを構築するための人気のあるプログラミング言語の一つです。 この言語の強みの一つは、特に数学関数を含む豊富な組み込み関数ライブラリにあります。 このチュートリアルでは、C#が提供するさまざまな数学関数を深く掘り下げ、Math クラスと一般的な数学的方程式を簡単に実行する方法に慣れるためのお手伝いをします。

はじめに

C#では、MathクラスSystem名前空間内で利用可能な静的クラスです。 このクラスには、開発者が一から書く必要なく数学的な操作を行うのを助けるために設計された、多数のメソッドが含まれています。

数学クラスへのアクセス方法

Mathクラスにアクセスするには、public class 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.<functionName> を参照して 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
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

高度な数学関数

より高度な操作を求める方へ:

Power: Math.Pow() 関数は、基数と指数の2つの整数を受け取ります。 それは指定されたべき乗に上げられた基数を返します。

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 クラスを使用します。 それは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

数学クラスの変換関数

開発者はしばしば異なる種類の数値を変換する必要があります。

整数への変換: ダブル型を持っていて、その小数を削除して整数に変換したい場合は、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

10進数から2進数: 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#の機能について掘り下げると、このプログラミング言語を取り巻くエコシステムが非常に進化してきたことに注目する価値があります。 そのような貢献の一つは、C#開発者向けに調整された包括的なツールキットであるIron Suiteの形で提供されています。 それは、アプリケーションを強化し、堅牢で機能豊富にする一連の製品を提供します。

IronPDF

C# 数学(開発者向けの仕組み) 図 1 - IronPDF

C#アプリケーションでPDFを操作する必要を感じたことはありますか? C#アプリケーションでPDF統合を行うためのIronPDFは、あなたの頼りになるソリューションです。 PDFファイルの作成、編集、そしてコンテンツの抽出が非常に簡単になります。 C#の数学関数と組み合わせると、レポート、グラフ、その他の数学的な可視化を生成し、それらをPDF文書にシームレスに埋め込むことができます。

IronPDFの際立った機能は、そのHTML to 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# Math(開発者向けの作動方法)図3 - IronOCR

光学文字認識 (OCR) は未来的な概念ではなく、画像やPDFからテキストを抽出するためのIronOCR で現実になっています。 アプリケーションで画像やスキャンされたドキュメントを扱っていて、特に数値データや数式を抽出したい場合、IronOCRをC#と組み合わせて使用することで、シームレスに認識して利用可能なデータに変換することができます。

IronBarcode

C# Math(開発者向けの仕組み)図4 - IronBarcode

今日の世界では、バーコードが製品識別において重要な役割を果たしています。 C#でのバーコード生成と読み取りのためのIronBarcodeを使用すると、C#開発者はバーコードを簡単に生成、読み取り、操作できます。 在庫管理システムやPOSシステムの開発において、数学的計算とバーコードが絡み合う場合に特に有用です。

結論

C# 数学 (開発者向けの仕組み) 図5 - ライセンス

C#の分野は広大で強力です。Iron Suiteのようなツールを使うことで、あなたのアプリケーションを新たな高さに引き上げることができます。 注目すべきは、Iron Suite内の各製品、たとえばIronPDF、IronXL、IronOCR、IronBarcodeは、$749から始まるライセンスから開始されます。 さらに、投資する前に試してみたい方のために、各製品はIron Suiteの豊富な機能の30日間無料試用(わずか2製品の価格で)を提供しています。 このような取引は、コスト節約を提供するだけでなく、さまざまな開発ニーズを満たすための包括的なツールキットも確保します。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C#のString Builder(開発者向けの動作原理)
次へ >
C# スイッチ式(開発者向けの動作方法)