Console input and output statements
output:
Console.WriteLine(); // new line
Console.Write();// no line break
enter:
Can save the entered content
Console.ReadLine();
Console.ReadKey();
If it is ReagKey(true), the entered content will not be displayed on the console
char c = Console.ReadKey(true).KeyChar;
empty:
Console.Clear();
Set console size:
window size, buffer size
Notice:
- Set the window size first, then the buffer size
- The size of the buffer cannot be smaller than the size of the window
- The size of the window cannot be larger than the maximum size of the console
Console.SetWindowSize(100,50); //window size
Console.SetBufferSize(1000,1000); //buffer size
Set the position of the cursor:
The upper left corner of the console is the origin 0, the right side of 0 is the positive direction of the X-axis, and the bottom is the positive direction of the Y-axis. It is a two-dimensional coordinate system
Notice:
- boundary question
- The horizontal and vertical distance units are different 1y = 2x visually
Console.SetCursorPosition(0,1);
set color related
Text color settings:
Console.ForegroundColor = ConsoleColor.Red;
Background color settings:
Console.BackgroundColor = ConsoleColor.White;
//After resetting the background color, you need to Clear once to change the entire background color
Console.Clear();
Show or hide the cursor
Console.CursorVisible = false;
close console
Environment.Exit(0);
breakpoint
- How to break point F9
- How to see the code logic F10 step by step
- Continue to stop and watch F5 step by step
You can view the desired variable value through the monitoring window
fold code
Only useful when editing, for folding code
#region
#endregion
random number
Fixed writing:
Random variable name = new Random();
Generate random numbers:
Random r = new Random();
int i = r.Next(); // Generate a non-negative random number
Console.WriteLine(i);
i = r.Next(100); // Generate a random number from 0 to 99 and the left side is always 0
i = r.Next(5,100); // Generate a random number from 5 to 99, including left and right
variable
14 variable types
An unsigned integer variable can store a certain variable type given range 0 and certificate
byte 0~255
ushort 0~65535
uint 0~4.2 billion
ulong 0~18 trillion
A signed integer variable can store a certain range of positive and negative numbers including 0 variable type
sbyte -128~127
short -32768~32767
int -2.1 billion~2.1 billion
long -9 trillion~9 trillion
float (decimal)
Float stores 7/8 significant digits and rounds significant digits to calculate from non-zero numbers. Decimals in c# are of double type by default. In order to distinguish the following + f/F double stores 15`17
significant digits and rounds
decimals to store 27~28 significant digits. It is not recommended to use, followed by +m/M
special type
bool true/false
char stores a single character charc = "A" character type
string string type is used to store multiple characters without upper limit
The range and type of storage of different variables are different, the essence is that the memory space occupied is different
variable nature
1byte = 8bit
1MB = 1024byte
1GB = 1024MB
1TB = 1024GB
The memory space occupied by the variable type can be obtained by the sizeof method (unit: byte)
int sbyteSize = sizeof(sbyte);
Console.WriteLine(sbyteSize);//1
int intSize = sizeof(int);
Console.WriteLine(intSize);//4
int shortSize = sizeof(short);
Console.WriteLine(shortSize);//2
int longSize = sizeof(long);
Console.WriteLine(longSize);//8
Bytes occupied by all variable types:
Signed:
sbyte 1 byte 8 bits
int 4 bytes 32 bits
short 2 bytes 16 bits
long 8 bytes 64 bits
unsigned:
byte 1 byte 8 bits
uint 4 bytes 32 bits
ushort 2 bytes 16 bits
ulong 8 bytes 64 bits
floating point:
float 4 bytes 32 bits
double 8 bytes 64 bits
decimal 16 bytes 128 bits
special:
char 2 bytes 16 bits
bool 1 byte 8 bits
string variable not fixed
The essence of variables is binary. The essence of all data in a computer is binary. It is a bunch of 0 and 1.
Data transmission can only be through electrical signals. There are only two states of on and off
. Can represent two numbers 0 and 1
Binary to decimal rules:
Looking from right to left, the rightmost bit is the 0th bit, if the bit is not 0, add 2 to the power of n bits
Variable naming convention
- can not be the same name
- cannot start with a number
- cannot be named using program keywords
- Can not have special symbols
constant
escape character
type conversion
implicit conversion
Large range to small range
double —> float —> integer (unsigned, signed) —> char
decimal —> integer (unsigned, signed) —> char
long —> int —> short —> sbyte
ulong —> uint —> ushort —> byte
Unsigned cannot implicitly store signed
Signed can implicitly store unsigned (note the range size)
example:
int a = 1;
short b = 1;
a = b;
//The type of b is converted to short
display conversion
1. Bracket conversion:
Role: cast high-precision types to low-precision, conversion between values
Syntax: variable type variable name = (variable type) variable;
Note: Precision Issues Range Issues
example:
short s = 1;
int i = 1;
s = (short)i;
Brackets forced into an exception
When a floating-point number is converted into an integer, the decimal after the decimal point will be discarded directly
bool and string cannot be cast through parentheses
2. Parse method
Function: convert the string type to the corresponding type
Syntax: VariableType.Parse("String")
Note: The string must be able to be converted into the corresponding type, otherwise an error will be reported; the range of the value sent must be a value that can be stored by the variable, otherwise an error will be reported
example:
int i = int.Parse("123");
Console.WriteLine(i);//123
3. Convert method
Role: more accurate conversion between various types
Syntax: Convert.To target type (variable or constant)
Higher precision, will be rounded
Each type has a corresponding Convert method
sbyte sb = Convert.ToSByte("1");
short s = Convert.ToInt16("1");
int i = Convert.ToInt32("1");
long l = Convert.ToInt64("1");
byte b = Convert.ToByte("1");
ushort us = Convert.ToUint16("1");
uint ui = Convert.ToUInt32("1");
ulong ul = Convert.ToUInt64("1");
float f = Convert.ToSingle("13.2");
double d =Convert.ToDouble("13.2");
decimal de = Convert.ToDecimal("13.2");
bool bo = Convert.ToBoolean("true");
char c = Convert.ToChar("A");
string str = Convert.ToString(123456);
4. Convert other types to string:
Function: Stitching and printing
Syntax: variable.ToString();
example:
string str = 123.ToString();
str = true.ToString();
str ='A'.ToString();
When we do string concatenation, tostring is automatically called
Console.WriteLine("123" 4 + true )
exception capture
Basic grammar:
//Mandatory part
try
{ //The code block that wants to capture exceptions //If the code in try reports an error, it will be executed in catch, }catch(Exception e)
{ // e specific error message } // optional part finally { // code that will be executed regardless of whether there is an error }
Example:
//必写部分
try
{
string str = "你好啊";
int i =int.Parse(str);
Console.WriteLine(i);
}
catch(Exception e)
{
Console.WriteLine("字符串不合法");
}
//可选部分
finally
{
Console.WriteLine("再见!");
}
arithmetic operator
Arithmetic operators are operators used to calculate variables of numeric type, and the return result is a numeric value
assignment symbol
=
Key knowledge points: first look at the right side, then look at the left side, and assign the value on the right side to the variable on the left side
arithmetic operator
add +
reduce -
take *
Division/Integer division will lose the decimals after the decimal point. If you want to use floating-point numbers to store, you must write them as floating-point numbers during operations.
Surplus %
Precedence of Arithmetic Operators
Do multiplication and division first, then addition and subtraction
Count inside the brackets first, then outside the brackets
Composite operators for arithmetic operators
Composite operator for itself = to do the operation by itself
+=
-=
*=
/=
%=
Arithmetic operator increment and decrement
++
i++: use first and then add
++i: add first and then use
--
i--: Use first and then subtract
--i: Subtract before using
string concatenation
1. Use + to splice
2、string.Format()
Syntax: string.Format("content to be spliced", content 1, content 2, content 3.......);
Rule: The content to be spliced is replaced by a placeholder {number} Number: 0~n, sequentially
example:
string str = string.Format("我是{0},我今年{1}岁,我想要{2}", "小明", 18, "好好学习,天天向上");
Console.WriteLine(str);//我是小明,我今年18岁,我想要好好学习,天天向上
If the following content is more than the placeholder, no error will be reported; if the following content is less than the placeholder, an error will be reported.
3. Console printing
The above method can be used directly
Console.WriteLine("我是{0},我今年{1}岁,我想要{2}", "小明", 18, "好好学习,天天向上");
conditional operator
Used to compare two variables or constants
Is it greater than>
Is it less than <
Is it equal to ==
Is not equal to !==
Is it greater than or equal to >=
Is it less than or equal to <=
The comparison result returns a value of bool type, true and false, returns true if the condition is satisfied, and returns false if the condition is not satisfied
Logical Operators
logic and
&& performs logical operations on two bool values, false is false and true is true
logical or
|| True is true and false is false
logical NOT
! Negates a bool value from true to false and from false to true
Mixed Use Priority Issues
! Highest priority && higher priority than ||
Logical operators have lower precedence than arithmetic operators Conditional operators (except !)
Logical operator short circuit rules
As long as && or || satisfies the condition on the left side, the expression on the right side will not be executed
bitwise operator
For calculations that mainly use numeric types, convert the value to binary, and then perform bit operations
bit and &
Connect two values for calculation, convert the value to binary bitwise operation, if there is 0, then 0
int a = 1; //001
int b = 5; //101
int c = a & b;
// 001 & 101 = 001 = 1
Console.WriteLine(c); // 1
bit or |
There are 1 and 1 in the bitwise operation
int a = 1; //001
int b = 3; //011
int c = a | b;
// 001 | 011 = 011 = 3;
Console.WriteLine(c); // 3
XOR ^
The same bit operation is 0, and the difference is 1
Bit inversion ~
Write in front of the value to convert the value to binary
Bitwise operation 0 to 1 1 to 0
int a = 5; // 0000 0000 0000 0000 0000 0000 0000 0101
int b = ~a;
// ~0000 0000 0000 0000 0000 0000 0000 0101
= 1111 1111 1111 1111 1111 1111 1111 1010 = -6
Shift Left<< and Shift Right>>
Let the binary number of a number be shifted left and right
Move a few bits to the left and add a few 0s to the right
int a = 5; // 101
int b = a << 5; // 10100000 =160
Move a few digits to the right and delete a few digits on the right
int a = 5; // 101
int b = a >> 2; // 1
Ternary operator
basic grammar
bool type? bool type is true return content: bool type is false return content;
conditional branch statement
Let the sequentially executed code branch
if statement
grammar:
if (bool type value)
{
}else{
}
Can be nested; else can be omitted
switch statement
Function: Let the sequentially executed code generate branches
grammar:
switch(variable)
{
case constants:
// The code logic that satisfies the conditional execution;
break;
case constants:
// The code logic that satisfies the conditional execution;
break;
default:
// If the conditions of the above case are not met, the code in default will be executed
break;
}
Notice:
- Constants can only write a value, not a range, conditional operators, logical operators
- switch only judges whether the variable is equal to a certain fixed value
- default can be omitted
Customizable constants:
char c = 'A';
const char c1 = 'A'; // must be initialized; cannot be modified
switch(c)
{
case c1:
Console.WriteLine("c is equal to A");
break;
}
Through:
Do not write the break after the case, if any case condition is met, the following code will be executed
int a = 1;
switch(a)
{
case 1:
case 2:
Console.WriteLine("is a number");
break;
default:
break;
}
//Output result: it is a number
while loop statement
Role: Let the code be executed repeatedly
grammar:
while (value of type bool)
{
//When the condition is met, the content in the while statement block will be executed
//......
//......
//......
// After the code logic is executed, it will return to the beginning of the while loop and judge the condition again
}
//Avoid writing dead loop
Nested use:
The while loop can not only nest if switch but also nest while
Process control keywords:
Role: Keyword to control loop logic
break: break out of the loop
while(true)
{
Console.WriteLine("1111");
break;
Console.WriteLine("2222");
}
Console.WriteLine("3333");
// 1111
// 3333
continue: Go back to the loop and start re-executing
break and continue are mainly used in conjunction with loops
do...while loop
The do while loop is to execute the logic in the loop statement block at least once before judging whether to continue
do
{
//...
} while (value of type bool);
for loop
for( /*initial expression*/ ; /*conditional expression*/ ; /*incremental expression*/ )
{
}