Trap 4 - Decimal Number

◀ Trap 3 - Another Type Cast▶ Trap 5 - The cin Operator
Amazon Dealing with decimals numbers can be tricky. Predict the output of the executing the following program. Pay attention to the very concept of how machines deal with a decimal number.
#include<iostream>
using namespace std;
int main(){
	int shape;
	double degree,transition;
	shape=17;
	transition=100.0/shape;
	degree=0;
	while(true){
		if(degree>100.0){
			cout<<degree<<" is greater than 100.0\n";
break; } else if(degree<100.0) cout<<degree<<" is smaller than 100.0\n"; else cout<<degree<<" is equal to 100.0\n"; degree+=transition; } return 0; }

Solution
Here is the output of the program:

0 is smaller than 100.0
5.88235 is smaller than 100.0
11.7647 is smaller than 100.0
17.6471 is smaller than 100.0
23.5294 is smaller than 100.0

29.4118 is smaller than 100.0
35.2941 is smaller than 100.0
41.1765 is smaller than 100.0
47.0588 is smaller than 100.0
52.9412 is smaller than 100.0
58.8235 is smaller than 100.0
64.7059 is smaller than 100.0
70.5882 is smaller than 100.0
76.4706 is smaller than 100.0
82.3529 is smaller than 100.0
88.2353 is smaller than 100.0
94.1176 is smaller than 100.0
100 is smaller than 100.0
105.882 is greater than 100.0

Notice how it differs from your expectations? Second to the last line says that 100 is smaller than 100.0, but how is that possible? We divide 100 by 17 and increment that amount 17 times, starting at 0. So we should end up with exactly 100 and the last line should read, “100 is equal to 100.0”!


Now try running the program again with the variable shape changed to 16, then you should get exactly what you expect to get. So how do we account for the fact that when 100 is split up to 17 portions evenly and we add them together, we do not get exactly 100?

As a matter of fact, machines have their ways of handling floating-point numbers. For more information, please visit http://www.mathworks.com/moler/. The book contains extensive information on how machines handle floating-point numbers.
By examining this example, you should learn that some bugs do not come from erroneous logic or syntax of the language but come from lack of understanding of how a compiler and an operating system work.


Understanding these may take a long time, but you still can avoid the above situation by trial and error. If you do see a problem, try a couple of alternatives and see if you can figure out the source of the problem. Only by gaining more experience will your skills improve.

Next let’s look at another input stream trap!
◀ Trap 3 - Another Type Cast▶ Trap 5 - The cin Operator

fShare
Questions? Let me know!