#这是关于Double与0之间的一个问题,也许是关于精度的一个问题。
#是无心知道的。具体如下:
#有没有开启c99会有这么大的区别吗?
#不知道这个算什么,但是很心疼。
$cat test.c
1 #include <stdio.h> 2 #include <math.h> 3 4 int main() 5 { 6 long double x; 7 long double step=0.01; 8 for(x=1.0; x>=-1.0; x-=step) { 9 printf("%Lf\n",x); 10 } 11 return 0; 12 }
#没有开启c99:
$gcc test.c $./a.out ......此处略出许多行 -0.950000 -0.960000 -0.970000 -0.980000 -0.990000 ####注意最后一行,可不是 -1.0哦!!!
#然后开启c99:
$gcc -std=c99 test.c $./a.out ......此处略出许多行 -0.950000 -0.960000 -0.970000 -0.980000 -0.990000 -1.000000 ####注意最后一行,输出正确哦哦哦~!!!
###后问百度,引申出另一个问题,浮点数的零其实不是零。
所以浮点数的比较不能单纯的 =0 或者 =-1.0。
应该设置一个精度,在此精度范围内,可以理解为相等。
So......
我写了一个输出心形的x、y坐标数据的程序,然后用gnuplot画图。
所以,详见 heart.cpp :
1 #include <iostream> 2 #include <fstream> 3 #include <cmath> 4 5 #define MIN_VALUE 1e-8 6 7 int main() 8 { 9 double x,y,t; 10 double step=0.01; 11 bool exit_or_not=false; 12 13 std::ofstream outfile; 14 outfile.open("heart.dat",std::ofstream::out); 15 16 for(x=-1.0; x<=1.0+step; x+=step) { 17 if( fabs(x-0.0)<MIN_VALUE ) { 18 x=0.0; 19 } 20 if( fabs(x-1.0)<MIN_VALUE ) { 21 x=1.0; 22 exit_or_not=true; 23 } 24 25 t = 1-x*x; 26 if(t<0) { 27 continue; 28 } 29 y = sqrt(t)+cbrt(x*x); 30 31 outfile << x << " " << y << std::endl; 32 33 if(exit_or_not) { 34 exit_or_not=false; 35 break; 36 } 37 } 38 39 for(x=1.0; x>=-1.0-step; x-=step) { 40 if( fabs(x-0.0)<MIN_VALUE ) { 41 x=0.0; 42 } 43 if( fabs(x+1.0)<MIN_VALUE ) { 44 x=-1.0; 45 exit_or_not=true; 46 } 47 48 t = 1-x*x; 49 if(t<0) { 50 continue; 51 } 52 y = -sqrt(t)+cbrt(x*x); 53 54 outfile << x << " " << y << std::endl; 55 56 if(exit_or_not) { 57 exit_or_not=false; 58 break; 59 } 60 } 61 62 63 return true; 64 }
关于gnuplot作图的细节,再说。