Computer Science I for non-majors by James Tam |
Floating point is the computers approximation of a real number. The real number is stored in three parts: one bit for the sign of the number to be stored (zero = positive, one = negative), a number of bits for the mantissa (the digits of the number to be stored) and the exponent (which determines the number of places that the decimal point will 'float' (thus the term floating point). The sign of the exponent specifies the direction of the shift when converting from floating point back to the original number. A negative exponent indicates a left shift while positive exponent indicates a right shift. Note: The sign of the exponent is not the same as the sign of the original number! Because the mantissa can only store a fixed number of digits it is possible that precision may be lost. The following examples will use a 5 digit mantissa.
Example 1 (number to be stored as float: 12345): Sign bit: 0 (positive) Mantissa: 12345 Exponent: 0 Number restored from floating point: 12345
Example 2 (number to be stored as float: -1234567): Sign bit: 1 (negative) Mantissa: 12345 Exponent: 2 Number restored from floating point: -1234500
Example 3 (number to be stored as float: -12): Sign bit: 1 (negative) Mantissa: 12000 Exponent: -3 Number restored from floating point: -12
Write a program that will prompt the user to enter an integer which will be stored in simulated floating point format. (Although it may seem strange to exclude fractional numbers in an assignment that is supposed to store a number in floating point format it was decided to exclude this requirement because if real numbers may also be entered you may end up errors in the results not due to a logic of your program but because the original number was not correctly stored as float). When you write your program you can assume that the input will be in the range of -123456789 to +123456789. The program will then represent this number in a simulated floating point form: <sign bit> <five digits for the mantissa> <exponent>. With only five digits for the mantissa, numbers that consist of more digits may not be stored correctly! The program will then 'reassemble' the number from the floating point representation. It should display the original number, it's floating point representation and finally the number that has been restored from the floating point representation (see Figure 1).
Figure 1: Sample execution |
Additional note for this assignment: you cannot use Strings or lists. (The number entered by the user and it's floating point components, for instance, must employ integer or Boolean variables only).