Files
BasicsOfComputerSoftwareEng…/07/Exercise01.c
2022-11-01 20:18:43 +08:00

37 lines
923 B
C

#include <stdio.h>
#include <math.h>
double f(double x);
double S(double a, double b, int m);
double f(double x) {
return pow(exp(1.0), -x*x);
}
double S(double a, double b, int m) {
double step = (b-a) / m;
double ans = 0;
int i = 0;
for (i = 0; i < m; i++) {
ans += step * (f(a + step * i) + f(a + step * (i + 1))) / 2;
}
return ans;
}
int main() {
double a, b;
int m;
double bestResult;
double lowerBond, upperBond;
bestResult = S(-1, 1, 2000);
printf("The best result we get is %.10lf\n", bestResult);
lowerBond = ((int)(bestResult * 10000)) / 10000.0;
upperBond = lowerBond + 0.0001;
for (m = 1; m <= 2000; m++) {
if (S(-1, 1, m) >= lowerBond && S(-1,1,m) < upperBond) {
printf("Now the first m that satisfies the requirment is %d, the result is %.10lf.", m, S(-1,1,m));
break;
}
}
return 0;
}