C# 値が正の数か負の数かを判定する

C#で、Signメソッドを使用して、値が正の数か負の数かを判定するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Microsoft Visual Studio Community 2019 Version 16.7.1
Signメソッド使い方
Signメソッドを使用すると、値が正の数か負の数かを判定することが可能です。
-1 : 負の数
0 : 0
1 : 正の数
1 2 3 4 5 6 7 8 9 10 11 |
double num1 = -2; // 符号の判定 Console.WriteLine(Math.Sign(num1)); // -1 double num2 = 2; // 符号の判定 Console.WriteLine(Math.Sign(num2)); // 1 double num3 = 0; // 符号の判定 Console.WriteLine(Math.Sign(num3)); // 0 |
サンプルコード
以下は、
textboxに入力した値の正の数か負の数かを判定して、別のtextboxに表示する
サンプルコードとなります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormTestApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // textBox1.Textの値を取得 double num = Convert.ToDouble(textBox1.Text); // 判定 double result = Math.Sign(num); // 結果をtextBox2.Textに値を表示 if (result == -1) { textBox2.Text = "負の数です"; }else if (result == 1) { textBox2.Text = "正の数です"; }else { textBox2.Text = "0です"; } } } } |
判定結果が表示されることが確認できます。

-
前の記事
javascript オブジェクトからキーのみを抽出する 2020.10.07
-
次の記事
javascript canvasタグを使用してテキストを書く 2020.10.08
コメントを書く