c - 宽度不为 1 时的梯形规则程序未完成 (C)

标签 c for-loop increment

通过(上限 - 下限)/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/

相关文章:

c - C中的自由指针是什么?

c - Anagram - 最小删除数量 - 某些测试用例失败

javascript - 为什么 console.log() 创建/**id :4**/and/**ref:4**/values?

c++ - 迭代器不是对象吗?

带有增量的 Java return 语句 - 一般行为是什么?

c - 指针算术的差异 (&x[5]-x)

c - 可变顺序对 sscanf 重要吗?

python - 如何遍历列表中除最后一项之外的所有内容?

javascript - 字符串增量 : increment the last string by one

javascript - 具有特定父输入的加号减号按钮不起作用