考虑以下两段代码 - 它们之间的唯一区别是单个 cout 打印值 eps:http:
//ideone.com/0bEeHz - 这里程序进入无限循环,因为 cout eps 将值更改为 0
#include <iostream>
int main()
{
double tmp = 1.;
double eps;
while(tmp != 0) {
eps = tmp;
tmp /= 2.;
}
if(eps == 0) {
std::cout << "(1)eps is zero!\n";
}
std::cout << "eps before: " << eps;
if(eps == 0) {
std::cout << "(2)eps is zero!\n";
}
while(eps < 1.) {
tmp = eps;
eps *= 2.;
if(tmp == eps) {
printf("wtf?\n");
}
}
std::cout << "eps after: " << eps;
}
http://ideone.com/pI4d30 - 在这里我已经注释掉了 cout。
#include <iostream>
int main()
{
double tmp = 1.;
double eps;
while(tmp != 0) {
eps = tmp;
tmp /= 2.;
}
if(eps == 0) {
std::cout << "(1)eps is zero!\n";
}
//std::cout << "eps before: " << eps;
if(eps == 0) {
std::cout << "(2)eps is zero!\n";
}
while(eps < 1.) {
tmp = eps;
eps *= 2.;
if(tmp == eps) {
printf("wtf?\n");
}
}
std::cout << "eps after: " << eps;
}
因此,一个单一的 cout 极大地改变了程序逻辑,非常令人惊讶。这是为什么?