帮忙看一看下面程序中两次调用时for的结束条件;

来源:百度知道 编辑:UC知道 时间:2024/05/11 02:19:59
帮忙看一看下面程序中两次调用时for的结束条件;
#include<iostream.h>
#include<math.h>

double sigma(double (*func)(double),double dl,double du)
{
double dt=0.0;
for(double d=dl;d<du;d+=0.1)
dt+=func(d);
return dt;
}

void main()
{
double dsum;
dsum=sigma(sin,0.1,1.0);
cout<<"the sum of sin from 0.1 to 1.0 is "<<dsum<<endl;
dsum=sigma(cos,0.5,3.0);
cout<<"the sum of cos from 0.5 to 3.0 is "<<dsum<<endl;
}
第一次调用for语句结束时:当d=1.00000000000000时,通过参数传递的du=1.00000000000000,而d<du的值却为1—-这个是怎么回事;
如果将for中d<du改为d<=du,运行结果不变;
大家可以在VC上调试一下,观察d,du,d<du及dt的值的变化;

改写成:
for(double d=dl;d<du;d+=0.1) {
cout << "d=" << d << endl;
dt+=func(d);
}

看出:
第1个for的结束条件 做完 d=1
第2个for的结束条件 做完 d=2.9

dsum=sigma(sin,0.1,1.0);
这次调用,for循环的结束条件是d==1

dsum=sigma(cos,0.5,3.0);
这次调用,for循环的结束条件是d==3

1次:d = 1.0 d不小于1.0了,循环结束
2: d=3.0, d不小于3.0了,循环结束。