这是我的源代码:
#include <iostream>
#include <cmath>
using namespace std;
double up = 19.0 + (61.0/125.0);
double down = -32.0 - (2.0/3.0);
double rectangle = (up - down) * 8.0;
double f(double x) {
return (pow(x, 4.0)/500.0) - (pow(x, 2.0)/200.0) - 0.012;
}
double g(double x) {
return -(pow(x, 3.0)/30.0) + (x/20.0) + (1.0/6.0);
}
double area_upper(double x, double step) {
return (((up - f(x)) + (up - f(x + step))) * step) / 2.0;
}
double area_lower(double x, double step) {
return (((g(x) - down) + (g(x + step) - down)) * step) / 2.0;
}
double area(double x, double step) {
return area_upper(x, step) + area_lower(x, step);
}
int main() {
double current = 0, last = 0, step = 1.0;
do {
last = current;
step /= 10.0;
current = 0;
for(double x = 2.0; x < 10.0; x += step) current += area(x, step);
current = rectangle - current;
current = round(current * 1000.0) / 1000.0;
//cout << current << endl;
} while(current != last);
cout << current << endl;
return 0;
}
它的作用是计算曲线之间的面积。 main() 中有一个循环 - 其目的是计算尽可能精确到小数点后 3 位的值。
它不起作用。为了调试的目的,我添加了唯一被注释的行。我想知道循环内部发生了什么。
//cout << current << endl;
当该行存在时 - 当我取消注释时 - 一切正常。如果不是的话 - 循环似乎是无限的。
神圣编译器,为什么?
据我所知,这不是不精确的浮点数的问题。循环内容在 4 次重复内完成when我正在输出其中的当前值。