1. 程式人生 > 實用技巧 >C# 中數字常見操作及其取值範圍

C# 中數字常見操作及其取值範圍

1.浮點數

  用於表示數量級可能非常大或者非常小的非整數;

  float:單精度浮點數表示用於儲存值的二進位制位數為32位

  double:雙精度浮點數相對於單精度浮點數而言,是其兩倍;即表示用於儲存值的二進位制位數為64位

2.常見算數運算   
   int c=7/4; //若值不為整數,商取整
  Console.WriteLine(c); //1
   double d = 7/4; //若值不為整數,商取整
  Console.WriteLine(d); //1
  d = 7/(4*1.0);
  Console.WriteLine(d);  //1.75

1
1
1.75

  
    int
c = 7 %4;   Console.WriteLine(c); //3,取餘   c =4 % 7;   Console.WriteLine(c); //4,取餘   int e = 11%7; //11%7   Console.WriteLine(e); //4   e = 7 % 11;   Console.WriteLine(e); //7

3
4
4
7
2.常見數值型別取值範圍
  
    int maxI = int.MaxValue;
  int minI = int.MinValue;
  Console.WriteLine($"The range of integers is {minI} to {maxI}
");

  The range of integers is -2147483648 to 2147483647

double maxD = double.MaxValue;
double minD = double.MinValue;
Console.WriteLine($"The range of double is {minD} to {maxD}");

The range of double is -1.79769313486232E+308 to 1.79769313486232E+308

其中E+308表示10的308次方

decimal min = decimal.MinValue;
decimal max = decimal.MaxValue; Console.WriteLine($"The range of the decimal type is {min} to {max}");
The range of the decimal type is -79228162514264337593543950335 to 79228162514264337593543950335
int what = maxI + 1;
Console.WriteLine($"int.MaxValue ={int.MaxValue}  int.MaxValue+1= {what}"); //最大整數加1剛好取反得到最小負數
what = maxI + 2;
Console.WriteLine($"int.MaxValue ={int.MaxValue}  int.MaxValue+2= {what}");

int.MaxValue =2147483647  int.MaxValue+1= -2147483648
int.MaxValue =2147483647  int.MaxValue+2= -2147483647
double和decimal型別比較
double a1 = 1.0;
double b1 = 3.0;
Console.WriteLine(a1 / b1);
0.333333333333333

decimal c1 = 1.0M;   //此處加M,類似float型別後面加f
decimal d1 = 3.0M;
Console.WriteLine(c1 / d1);
0.3333333333333333333333333333