0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#学習~型変換~

Posted at

C#の学習記録。
型変換について頭がこんがらがりそう…。

データ型が異なる物同士の演算

■暗黙の型変換

自動的にいずれかの型に揃えて演算が行われる。

変換元 変換先
int long,float,double,decimal
char ushort,int,uint,long,ulong,float,double,decimal

・右辺に型が混在する場合
変換元から変換先に一時的に型変換されてから演算される。

int a = 10;
double x = 3.2, y;
y = x * a;  //右辺はdouble型で演算される。

・代入する場合

int a = 10;
double x = a; // 自動的に左辺の型に変換され、aが10.0になる。

■明示的な型変換

どの型に変換するのか明示的に変換する事。

(例)
右辺の小さな方に右辺の大きな型を代入する場合、
収まりきらないのでエラーが出る。

int a;
double x = 123.456;
a = x; //エラーが生じる。

なので強制的に代入したい場合、キャスト演算子を使う!
※小数点以下を切り捨てたいという場合以外はaをdoubleで宣言する事!

int a;
double x = 123.456;
a = (int)x; //double型のxをint型にキャスト(変換)し、a = 123 になる。

■文字列型と他の型で演算を行う場合

・文字列型に他のデータ型を代入する場合

データ.ToString()
int a = 10;
double x = 123.456;
string s1 = a.ToString(); //"10" に変換
string s2 = x.ToString(); //"123.456"に変換
string s3 = 789.ToString(); //"789"に変換

・文字列型を他のデータ型に代入する場合
任意のデータ型に変換できる。

データ型.Parse(文字列)
string s1 = "12345";
int a = int.Parse(s1); // aは12345
double x = double.Parse("3.14"); //xは3.14

■除算の演算によって小数点以下が失われないようにする場合

整数同士の除算を行うと小数点以下は切り捨てられる。
なので明示的な型変換を行い小数点以下を残す!

double a = 5 / 2;  
// 明示的な型変換を行わないとa = 2.0となる。

double x = (double)5 / 2; 
// 5がdouble型として扱われ、「5.0 / 2」は暗黙の型変換により結果は「2.5」となる。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?