C # programming (2 _ type conversion ),

Source: Internet
Author: User

C # programming (2 _ type conversion ),

No matter what type, all data is a series of BITs, that is, 0 and 1. The meanings of variables are expressed by interpreting these programs. The simplest type is char, which uses a number to represent a character in the Unicode Character Set. In fact, this number is exactly the same as the ushort storage method-they are all stored in 0 ~ In the range of 65535.

However, in general, different types of variables use different modes to represent data, which means that even if a series of BITs are moved from one type of variables to another type of variables, the results are often different from expected.

This is not a one-to-one ing between data spaces from one variable to another, but a conversion of data types. Implicit conversion and display conversion are supported for type conversion.

  Implicit conversion: The conversion from type A to type B can be performed in all cases. The conversion rules are relatively simple and can be executed by the compiler. Conversion rules: Any Type A can be implicitly converted to type B if its value range is completely within the value range of type B;

  Display Conversion: Conversions from type A to type B can only be performed in some cases. The conversion rules are complex and require some type processing.

See the following example:

// Try to convert the short value to byte value byte destinationVar; short sourceVar = 7; destinationVar = sourceVar; Console. writeLine ("sourceVar: {0}", sourceVar); Console. writeLine ("destinationVar: {0}", destinationVar );

If you compile this code, the following error occurs:

Cannot implicitly convert type 'short 'to 'byte'. An explicit conversion exists (are you missing a cast ?)

To introduce the syntax of forced conversion (forcing data to be converted from one type to another) is relatively simple: <(destinationVar type) sourceVar>, that is, changed:

byte destinationVar;short sourceVar=7;destinationVar=(byte)sourceVar;Console.WriteLine("sourceVar:{0}",sourceVar);Console.WriteLine("destinationVar:{0}",destinationVar);

 

This will convert the value of the short Type in <sourceVar> to the value of the byte type in <destinationVar>. Of course, this is only feasible in some cases. types that have almost no relationships with each other or that have no relationships at all cannot be forcibly converted.

When the displayed data is converted from one type to another, data overflow may occur because the value range of the source variable is often different from that of the target variable, we can parse the data stored by the data itself (beginning with a series of BITs.

Two keywords checked and uncheked are used to check overflow, which are called the context of expression overflow.

byte destinationVar;short sourceVar=7;destinationVar=checked((byte)sourceVar);Console.WriteLine("sourceVar:{0}",sourceVar);Console.WriteLine("destinationVar:{0}",destinationVar);

If you modify the value of the sourceVar variable to make it greater than 255, the execution program will encounter an error and prompt overflow.

Of course, there is also the Convert command, which is also used to display the type conversion, the following is an example of all the above types conversion:

namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            short shortResult, shortVar = 4;            int integerVar = 67;            long longResult;            float floatVar = 10.5F;            double doubleResult, doubleVar = 99.999;            string stringResult, stringVar = "17";            bool boolVar = true;            Console.WriteLine("Variable Conversion Examples\n");            doubleResult = floatVar * shortVar;            Console.WriteLine("Implicit,->double:{0}*{1}->{2}", floatVar, shortVar, doubleResult);            shortResult = (short)floatVar;            Console.WriteLine("Implicit,->short:{0}->{1}", floatVar, shortResult);            stringResult = Convert.ToString(boolVar) + Convert.ToString(doubleVar);            Console.WriteLine("Implicit,->string:\"{0}\"+\"{1}\"->{2}", boolVar, doubleVar, stringResult);            longResult = integerVar + Convert.ToInt64(stringVar);            Console.WriteLine("Mixed,   ->long:{0}+{1}->{2}", integerVar, stringVar, longResult);            Console.ReadKey();        }    }}

 


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.