通过(上限 - 下限)/n(所需的梯形数)找到宽度的方式,在我的代码中,当宽度为 1 时它可以工作,但是如果它不是 1,程序将无法自行完成,我怀疑问题是我如何在“func”的 for 循环中递增它
代码:
#include <stdio.h>
#include <stdlib.h>
double func(double x) {
return x * x;
}
double trap(double lower, double upper, int n) {
double width,area = 0;
width = (upper - lower) / n;
//printf("%lf\n",width);
int i;
for (i = lower; i < upper; i += width) {
area += (func(i) + ((func(i + width)))) / 2 * width;
//printf("%lf\n",area);
}
return area;
}
int main(void) {
double lower,upper,x;
int n;
while (1) {
printf("lower limit: ");
scanf("%lf",&lower);
printf("upper limit (should be greater than %.2lf): ",lower);
scanf("%lf",&upper);
if (upper <= lower) {
printf("[ERROR] the lower limit must be less");
printf("than the upper limit: please try again\n");
continue;
}
printf("number of trapezoids: ");
scanf("%d",&n);
if (n <= 0) {
printf("[ERROR] the number of trapezoids must be");
printf("greater than 0; please try again\n");
continue;
}
break;
}
printf("%lf\n", trap(lower,upper,n));
return 0;
最佳答案
问题在于循环增量。将宽度从 double 转换为 int 时,double 的小数部分将被丢弃。这会导致(不包含)-1.0 和 1.0 之间的任何宽度值转换为 0。
关于c - 宽度不为 1 时的梯形规则程序未完成 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441608/