• Welcome to ComeFromChina Community (CFC中文网)! We are the largest Chinese Canadian community forum in Ottawa. Please to participate in discussions, post topics, view images, and access full community features. Join us today! 欢迎来到CFC中文网。请登录以参与讨论、发布主题并查看图片。

请教一下C++程序

#include <iostream>

using namespace std;

int main(){

double x1=9.0;
double x2=10.0;

while (0.1 < (x2-x1)){
x2=x2-0.1;
}
cout << x1 << " " << x2 << endl;
system("pause");

}


按照您的建议,改了判断,但结果仍是依旧。

将x1, x2定义为float类型,最后的输出是: 9, 9.1
而将x1, x2定义为double类型, 最后的输出是: 9, 9

为什么?

应该用 x1+0.1-x2 <0.00001. 假设5 位精度足够的话。
 
问题出在精度上,运行一下下面的程序就明白了

#include <iostream>
#include <iomanip>

using namespace std;

int main(){

double x1=9.0;
double x2=10.0;

cout << setprecision(17) << endl;

while (x1 < (x2 - 0.1)){
x2=x2-0.1;
cout << x2 << endl;
}
cout << x1 << " " << x2 << endl;

}
 
问题出在精度上,运行一下下面的程序就明白了

#include <iostream>
#include <iomanip>

using namespace std;

int main(){

double x1=9.0;
double x2=10.0;

cout << setprecision(17) << endl;

while (x1 < (x2 - 0.1)){
x2=x2-0.1;
cout << x2 << endl;
}
cout << x1 << " " << x2 << endl;

}


明白了,谢谢。
 
后退
顶部
首页 论坛
消息
我的