c++ - 关于 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();
推荐阅读
- gstreamer - 没有这样的元素或插件'v4l2h264enc'
- python - 如何解决未来的警告错误
- javascript - 用 props 填充 antd 表单域
- flutter - Json int 对 Flutter 进行双重解析
- elasticsearch - 在 Elasticsearch 中有两个节点的集群中启用安全性
- reactjs - 如何使用 react-hook-form 和 useContext 在 MultiStepForm 中存储值?
- opengl - 具有固定位置的 OpenGL 广告牌
- reactjs - 有没有办法在 Outsystems 中注销特定用户?
- r - 如何通过链接我的 csv 文件使我闪亮的应用程序对我的过滤器产生反应
- angular - 在多列中显示 formArray 输入