隱式轉換主要是在整型、浮點型之間的轉換,將儲存範圍小的資料型別直接轉換成儲存範圍大的資料型別。
例如將 int 型別的值轉換成 double 型別的值,將 int 型別的值轉換成 long 型別的值,或者將 float 型別的值轉換成 double 型別的值。
示例**如下。
int a =
100;
double d = a;
//將int型別轉換為double型別
float f =
3.14f
;d = f;
//將float型別轉換為double型別
隱式數值轉換包括以下幾種:
從 sbyte 型別到 short,int,long,float,double,或 decimal 型別。
從 byte 型別到 short,ushort,int,uint,long,ulong,float,double,或 decimal 型別。
從 short 型別到 int,long,float,double,或 decimal 型別。
從 ushort 型別到 int,uint,long,ulong,float,double,或 decimal 型別。
從 int 型別到 long,float,double,或 decimal 型別。
從 uint 型別到 long,ulong,float,double,或 decimal 型別。
從 long 型別到 float,double,或 decimal 型別。
從 ulong 型別到 float,double,或 decimal 型別。
從 char 型別到 ushort,int,uint,long,ulong,float,double,或 decimal 型別。
從 float 型別到 double 型別。
其中,從 int,uint 或 long 到 float 以及從 long 到 double 的轉換可能會導致精度下降,但決不會引起數量上的丟失。其它的隱式數值轉換則不會有任何資訊丟失。
convert 方法是資料型別轉換中最靈活的方法,它能夠將任意資料型別的值轉換成任意資料型別,前提是不要超出指定資料型別的範圍。
具體的語法形式如下
資料型別 變數名 = convert.to資料型別(變數名)
;
這裡 convert.to 後面的資料型別要與等號左邊的資料型別相匹配。
convert 類常用的型別轉換方法如下表所示。
方法說明
convert.toint16()
轉換為整型(short)
convert.toint32()
轉換為整型(short)
convert.toint64()
轉換為整型(short)
convert.tochar()
轉換為字元型(char)
convert.tostring()
轉換為字串型(string)
convert.todatetime()
轉換為日期型(datetime)
convert.todouble()
轉換為雙精度浮點型(double)
conert.tosingle()
轉換為單精度浮點型(float)
對於整型和浮點型的強制資料型別操作也可以使用 convert 方法代替,但是依然會損失儲存範圍大的資料型別的精度。
【例項】使用 convert 方法將分別將乙個浮點型資料轉換成整型和字串型。
根據題目要求,**去下。
class
program
", integer)
; console.
writeline
("轉換為字串,"
,str);}
}
執行上面**,效果如下圖所示。
Delphi 型別轉換筆記
一.byte word integer幾種資料型別的相互轉換 1.取byte值,然後轉換成2進製字串,然後字串相加,再轉換為int的,但太羅嗦了 integer byte1 shl 8 integer byte2 2.使用巨集 word makeword byte blow,bhigh 例如 fun...
JS型別轉換(筆記)
方式 說明案例 tostring 轉成字串 var num 1 alert num.tostring string 強制轉換 轉成字串 var num 1 alert string num 加號拼接字串和字串拼接的結果都是字串 var num 1 alert num 我是字串 方式說明 案例pars...
C 筆記(2) 資料型別轉換
1 將一種型別的值賦值給另一種型別的變數,則自動轉化為接收型別的變數。2 表示式中包含不同型別時,對值進行轉換。在計算表示式時,c 將bool char unsigned char signed char和short值轉化為int,true轉化為1,false轉化為0,這些稱為整形提公升 integ...