关于C++while循环的语法混淆
我最近开始学习 C++,我有一个关于我们讲座中关于声明不同类型变量时的准确性的练习的语法问题,在这种情况下是float和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 ;
}
所以我不明白的是,这里的重点是什么?怎么了?
回答
在 C++ 中,缩进不会影响程序的流程,但会影响可读性。
这可以更好地写为:
#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 ;
}
while 循环将对下一条语句进行操作。如果使用大括号,它会将大括号中的块视为语句。否则,它只会使用下一个语句。
以下片段是相同的:
while(1)
{
do_stuff();
}
do_other_stuff();
while(1) do_stuff(); do_other_stuff();
while(1)
do_stuff();
do_other_stuff();