C # "pitfalls" of float and double"

Source: Internet
Author: User

Define a float type variable = 0.7, but the result is 0.69999999 in Il.

Multiply by 10 to obtain the integer. The result is 6. By checking the Il, it is converted to the double type before conversion. It becomes 6.

Demo:

Il:

. Method private hidebysig static void main (string [] ARGs) cel managed {. entrypoint // code size 93 (0x5d ). maxstack 2 // define the variable. locals Init ([0] float32 Val, [1] int32 I) il_0000: NOP il_0001: LDC. r4 0.69999999 // assign 0.69999999 to 0th variables. It is clearly defined as 0.7 il_0006: stloc.0 il_0007: LDC. i4.s 10/assign 10 to the first variable il_0009: stloc.1 // 0.7 il_000a: LDC of the double type. r8 0.69999999999999996 il_0013: ldloc.1 il_0014: Conv. r8 il_0015: Mul il_0016: Call float64 [mscorlib] system. math: floor (float64) il_001b: Call void [mscorlib] system. console: writeline (float64) il_0020: NOP il_0021: ldloc.0 il_0022: Call void [mscorlib] system. console: writeline (float32) il_0027: NOP // load Val il_0028: ldloc.0 // load I il_0029 from the stack: ldloc.1 // convert I to the float type il_002a: Conv. r4 // Val * I il_002b: Mul // convert the result after multiplication to the double type il_002c: Conv. r8 // call math. floor: il_002d: Call float64 [mscorlib] system. math: floor (float64) il_0032: Call void [mscorlib] system. console: writeline (float64) il_0037: NOP il_0038: ldloc.0 il_0039: Conv. r8 il_003a: Call void [mscorlib] system. console: writeline (float64) il_003f: NOP il_0040: ldloc.0 il_0041: ldloc.1 il_0042: Conv. r4 il_0043: Mul il_0044: Conv. r8 il_0045: Call void [mscorlib] system. console: writeline (float64) il_004a: NOP il_004b: ldloc.0 il_004c: Conv. r8 il_004d: ldloc.1 il_004e: Conv. r8 il_004f: Mul il_0050: Call void [mscorlib] system. console: writeline (float64) il_0055: NOP il_0056: Call string [mscorlib] system. console: Readline () il_005b: Pop il_005c: Ret} // end of method program: Main

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.