Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Why does the following program output the second printf statementand not the fir

ID: 3609003 • Letter: W

Question

Why does the following program output the second printf statementand not the first ?
Why is (a+b+1) = 1 while (a+1+b) = 0 ?
Will rate lifesaver...thanks!

#include <stdio.h> #include <iostream> #include <math.h>
using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout <<a+b+1<<endl; cout<<a+1+b<<endl; if ( (a+b+1) == (a+1+b) ) { printf("Good ! "); } else { printf("Hmmm ? ... "); } return 0; }
Why is (a+b+1) = 1 while (a+1+b) = 0 ?
Will rate lifesaver...thanks!

#include <stdio.h> #include <iostream> #include <math.h>
using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout <<a+b+1<<endl; cout<<a+1+b<<endl; if ( (a+b+1) == (a+1+b) ) { printf("Good ! "); } else { printf("Hmmm ? ... "); } return 0; } Why is (a+b+1) = 1 while (a+1+b) = 0 ?
Will rate lifesaver...thanks!

#include <stdio.h> #include <iostream> #include <math.h>
using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout <<a+b+1<<endl; cout<<a+1+b<<endl; if ( (a+b+1) == (a+1+b) ) { printf("Good ! "); } else { printf("Hmmm ? ... "); } return 0; }
#include <stdio.h> #include <iostream> #include <math.h>
using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout <<a+b+1<<endl; cout<<a+1+b<<endl; if ( (a+b+1) == (a+1+b) ) { printf("Good ! "); } else { printf("Hmmm ? ... "); } return 0; } #include <stdio.h> #include <iostream> #include <math.h>
using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout <<a+b+1<<endl; cout<<a+1+b<<endl; if ( (a+b+1) == (a+1+b) ) { printf("Good ! "); } else { printf("Hmmm ? ... "); } return 0; }

Explanation / Answer

please rate - thanks I added some output and the reason is... not every floating point number is representable in acomputer. a and b are opposites of each other so add themtogether you get 0. 0+1 = 1. obviously the value of a + 1, cannot be represented. It is roundedto the value of a. so even though you've added 1 to a, a isunchanged, now add it's opposite and the result is 0. see this site       http://babbage.cs.qc.edu/IEEE-754/References.xhtml #include #include #include #include using namespace std; int main() { float a = 4.68 * pow(2.0,100); /* 4.68 x 2 ^ 100*/ float b = -1 * 4.68 * pow(2.0,100); cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote