C#急速入门-数字类型 - 2

137 阅读1分钟

整型

四则运算: +-*/

外加括号改变优先级

% 去余数

int a = 5;
int b = 4;
int c = 2;
int d = (a + b) - 6 * c + (12 * 4) / 3 + 12;
Console.WriteLine(d);
int e = (a + b) % c
Console.WriteLine(e);

获取整数类型范围

int max = int.MaxValue;
int min = int.MinValue;
Console.WriteLine($"The range of integers is {min} to {max}");

数据溢出的行为

max + 3不会报错,相当于min + 2

int what = max + 3;
Console.WriteLine($"An example of overflow: {what}");

浮点型

这里没有强调float和double的区别,文档说double更常用

四则运算: +-*/,外加括号改变优先级以及最值,这里说一下最值,因为结果是用科学计数法来展现的,E后面代表10的多少次方。

double max = double.MaxValue;
double min = double.MinValue;
Console.WriteLine($"The range of double is {min} to {max}");
// The range of double is -1.79769313486232E+308 to 1.79769313486232E+308

数字型 decimal - dai se mao

这是c语言没有的,一个新类型的出现,肯定是有目的。我觉得应该是更加方便使用或者更简洁。只是推测。

The decimaltype has a smaller range but greater precision than double .

文档说我很小,我很准。

数据范围以及精度

decimal min = decimal.MinValue;
decimal max = decimal.MaxValue;
Console.WriteLine($"The range of the decimal type is {min} to {max}");

double a = 1.0;
double b = 3.0;
Console.WriteLine(a / b);


decimal c = 1.0M;
decimal d = 3.0M;
Console.WriteLine(c / d);

小提示 输入小数的时候没有后缀,编译器会默认认为输入的是double类型

decimal e = 1.0;
decimal f = 3.0;
Console.WriteLine(e / f);

(1,13): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type e radius = 2.50; double area = Math.PI * radius * radius; Console.WriteLine(area);

Challenge

Now that you've seen the different numeric types, write code that calculates the area of a circle whose radius is 2.50 centimeters. Remember that the area of a circle is the radius squared multiplied by PI. One hint: .NET contains a constant for PI, Math.PI that you can use for that value. Math.PI, like all constants declared in the System.Math namespace, is a double value. For that reason, you should use double instead of decimal values for this challenge.

double radius = 2.50;
double area = Math.PI * radius * radius;
Console.WriteLine(area);