Reputation: 161
I recently started to learn C++ and I have a question regarding the syntax of an exercise given in our lecture about the accuracy when we declare different types of variables, in this case float
and double
.
#include <iostream>
using namespace std ;
int main()
{
// Accuracy test with float
float eps_f = 1.0 ;
while (float(1.0 + eps_f) != 1.0)
eps_f /= 2.0 ;
cout << "Resolving capacity float approximately: " << 2*eps_f << endl ;
// Accuracy test with double
double eps_d = 1.0 ;
while (1.0 + eps_d != 1.0)
eps_d /= 2.0 ;
cout << "Resolving capacity double approximately : " << 2*eps_d << endl ;
}
So what I don't understand is what is the point of while here? What is happening?
Upvotes: 2
Views: 148
Reputation: 2095
In C++, indentation does not affect the flow of a program, but it DOES affect the readability.
This can be better written as:
#include <iostream>
using namespace std ;
int main()
{
// Accuracy test with float
float eps_f = 1.0 ;
while (float(1.0 + eps_f) != 1.0)
{
eps_f /= 2.0 ;
}
cout << "Resolving capacity float approximately: " << 2*eps_f << endl ;
// Accuracy test with double
double eps_d = 1.0 ;
while (1.0 + eps_d != 1.0)
{
eps_d /= 2.0 ;
}
cout << "Resolving capacity double approximately : " << 2*eps_d << endl ;
}
A while loop will operate on the next statement. If braces are used, it will treat the block enclosed in the braces as a statement. Otherwise, it will only use the next statement.
The following snippets are identical:
while(1)
{
do_stuff();
}
do_other_stuff();
while(1) do_stuff(); do_other_stuff();
while(1)
do_stuff();
do_other_stuff();
Upvotes: 8
Reputation: 62553
Indentation matters!
Here is the snippet re-written by adding sane indentation:
while (float(1.0 + eps_f) != 1.0)
eps_f /= 2.0;
Now it is clear that while loop is executed until sum of 1.0
and eps_f
becomes 1.0
- meaning that eps_f
became so small that floating point math can not account for it.
Same change can be applied to the second while
snippet with double.
Upvotes: 3