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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With