[C# Basic Explanation] (6) Type conversion

6.1 Implicit type conversion

It is required that the types of the operands participating in the operation on both sides of the equal sign must be the same. If they are inconsistent, automatic type conversion will occur if the following conditions are met, or it is called implicit type conversion.

Requirements: The two types are compatible, and the target type is greater than the original type

For example: int and double are compatible (both are numeric types)

For example: double>int (small to large)

6.2 Display Type Conversion

The two types are compatible int-->double

The big one is converted into a small double-->int

grammar:

target type variable name = (target type) original value

Example of explicit type conversion:

static void Main(string[] args)
{
    double d = 5673.74;
    int i;
    // 强制转换 double 为 int
    i = (int)d;
    Console.WriteLine(i);
    Console.ReadKey();    
}

Output result:

5673

Disadvantages: loss of precision, loss of data

6.3 Mandatory type conversion

Implicit type conversion and explicit type conversion are both unsafe type conversions because data loss will occur. So C# provides two methods: Parse method and Convert method.

6.3.1 Parse method

The Parse method is used to convert the string type into any basic type. Here, the data types on the left and right sides of the equal sign are required to be compatible. The function of Parse is to convert the string type into the corresponding data type.

Notice:

① If the string content is empty or null, an ArgumentNullException is thrown.

② If the content of the string is not a number, a FormatException is thrown.

③ If the number represented by the string content exceeds the range that can be represented by the specified data type, an OverflowException is thrown.

method

illustrate

int.Parse(string value)

String type conversion to integer type (int)

char.Parse(string value)

String type conversion to character type (char)

double.Parse(string value)

String type conversion to double precision floating point type (double)

Single.Parse(string value)

String type conversion to single precision floating point type (float)

int i = int.Parse(“111”);
i++;
Console.WriteLine(i);

Output result: 112

6.3.2 TryParse method

The TryParse method also converts the string of digital content into an int type, but this method is superior to int.Parse in that it does not cause exceptions.

Returns true if the conversion was successful, and false if the conversion failed.

Obviously, the last parameter is the output value, if the conversion fails, the output value is 0; if the conversion is successful, the corresponding value is output.

语法:int.TryParse(string s, out int result)

Code example:

Console.Write("请输入int类型的整数:");
int result = 0;
bool b = int.TryParse(Console.ReadLine(),out result);
if(b)
{
    Console.WriteLine($"您输入的数字为{result}");
}
else
{
    Console.WriteLine("输入错误!");
}

6.3.3 Convert method

If the types of the two variables are compatible, you can use automatic type conversion or forced type conversion, but if the two types of variables are not compatible, such as string and int, then we can use a conversion factory called Convert to convert.

The Convert method is the most flexible method in data type conversion. It can convert the value of any data type into any data type, provided that it does not exceed the range of the specified data type.

Notice:

① To use Convert to convert, one condition must also be met: "It must be passable on the surface".

For example: string a= "123"/ can be converted into int or double

string b= "123abc"/ cannot be converted into int or double

② After the floating-point number is converted to int type data, the rounding calculation is performed.

③ This method cannot be used to handle the char type, otherwise an exception will be reported.

C# provides the following built-in type conversion methods

method

illustrate

Convert.ToInt32()

Convert to integer type (int)

Convert.ToChar()

Convert to character type (char)

Convert.ToDouble()

Convert to double-precision floating-point type (double)

Convert.ToSingle()

Convert to single-precision floating-point type (float)

Convert.ToString()

Convert to string type (string)

Convert.ToDateTime()

Convert to date type (datetime)

Code examples for converting different value types to string types
static void Main(string[] args)
{
    int i = 75;
    float f = 53.005f;
    double d = 2345.7652;
    bool b = true;
    Console.WriteLine(i.ToString());
    Console.WriteLine(f.ToString());
    Console.WriteLine(d.ToString());
    Console.WriteLine(b.ToString());
    Console.ReadKey();
}

Output result:

75

53.005

2345.7652

True

6.3.4 Type conversion exercises

Swap Variables Exercise

Method 1: Use a temporary variable

There are two ways to convert the input string to an int value: ①int.Parse(string s) and ②Convert.ToInt32(string value). Define a temporary variable temp, assign the value of x to temp, then assign the value of y to x, and then assign the value of x stored in temp to y; (It can be understood in this way: it is equivalent to an empty cup, a cup of coffee, a cup of milk, swap milk and coffee)

Console.WriteLine("请输入两个整数x,y");
//使用 int.parse(string s) 将输入的字符串为int值 
int x = int.Parse(Console.ReadLine());
//使用Convert.ToInt32(string value)将输入的字符串转化为int值
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("x={0},y={1}", x, y);
int temp;//定义一个临时变量temp
temp = x;  //将x的值赋给temp
x = y;     //将y的值赋给x
y = temp;  //将temp存放的x的值赋给y
Console.WriteLine("x={0},y={1}",x,y);
COnsole.ReadKey();

Method 2: Use addition and subtraction

Assign the value of the sum of x+y to x (with the value of y unchanged). The value of x minus the value of the original y is the value of x, and the obtained value of x is assigned to y. Then subtract the value of y obtained in the previous step (actually the original value of x) from x to get the current value of x (the original value of y).

Console.WriteLine("输入两个整数x,y");
int x = int.Parse(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("x={0},y={1}", x, y);
x = x + y;  //将x+y的和的值赋给x
y = x - y;  //这个x-y等于x和y的和减去原先y的值剩余原先x的值
x = x - y;  //这个x-y等于x+y的和减去y的值(y在上一步已经变成原先x的值),剩余原先的y的值
Console.WriteLine("x={0},y={1}", x, y);
COnsole.ReadKey();
Seconds Converter Exercise

Prompt the user to enter a string of numbers and convert the string of numbers into days, hours, minutes, and seconds

Console.WriteLine("请输入要计算的秒数:");
string inputSec = Console.ReadLine();
int seconds = Convert.ToInt32(inputSec);
//先转换有多少整数天,不足一天的转换有多少整数小时,不足一小时的转换有多少分钟,不足一分钟的剩余多少秒
int day = seconds / 86400;//天数
int hour = (seconds % 86400) / 3600;//秒数
int mins = (seconds % 86400) % 3600;//分钟
int min = mins / 60;//分钟
int sec = mins % 60;//秒数
Console.WriteLine($"计算后是{day}天:{hour}小时:{min}分钟:{sec}秒");
COnsole.ReadKey();
Determine whether it is a leap year

Two conditions:

1) The year is divisible by 400: century leap year 2000

2) The year is divisible by 4 but not divisible by 100: ordinary leap year 2004

Console.WriteLine("请输入年份,我来帮你判断是否为闰年");
int year = Convert.ToInt32(Console.ReadLine());
bool isRun = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
Console.WriteLine(isRun);
//逻辑或的优先级是低于逻辑与的优先级的
Console.ReadKey();

Guess you like

Origin blog.csdn.net/Y1RV1NG/article/details/129539547