首页 > 解决方案 > 关于 C++ while 循环的语法混淆

问题描述

我最近开始学习 C++,我有一个关于在我们的讲座中给出的关于声明不同类型变量时的准确性的练习的语法问题,在这种情况下floatdouble.

#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++

解决方案


在 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();

推荐阅读