首页 > 解决方案 > Unexpected result in integration of a function

问题描述

I try to create a program that computes the integral xx with specific limits but it seems that when I run the code the result doesn't seems right. For example, the integral of xx with limits 0 and 1 should be around 0.7834 and the result of my program shows 0.372762

Can you help me to figure the problem out?

The following code compiles with no warnings or errors.

#include <stdio.h>
#include <math.h>

int main() {
    double a,b,c;
    int i;
    c=0;
    printf("Insert limit 1:");
    scanf("%lf",&a);
    printf("Insert limit 2:");
    scanf("%lf",&b);
    for( i = 0; i < ((b-a)*1000); i = i + 1 ){
      c=c+0.001*pow(a,a);
      a=a+0.001;
   }
   printf("The area is %lf", c);
    return 0;
}

标签: c

解决方案


重新形成for()循环以迭代和精确的整数次。

OP的; 代码正在更改a每个循环,因此i < ((b - a) * 1000不会导致正确的迭代计数。@迈克尔

#include <stdio.h>
#include <math.h>

int main() {
  double a, b, c;
  int i;
  c = 0;
  printf("Insert limit 1:\n");
  a = 0; //scanf("%lf",&a);
  printf("Insert limit 2:\n");
  b = 1.0; /// scanf("%lf",&b);
#if 0
  for (i = 0; i < ((b - a) * 1000); i = i + 1) {
    c = c + 0.001 * pow(a, a);
    a = a + 0.001;
  }
#else
  double delta = (b - a) / 1000;
  for (i = 0; i < 1000; i = i + 1) {
    c = c + delta * pow(a, a);
    a = a + delta;
  }

#endif
  printf("The area is %lf\n", c);
  return 0;
}

输出

The area is 0.783431

推荐阅读