提问者:小点点

C: 具有无限环的黎曼积分问题


我必须写一个程序来计算正弦循环。第一个任务是,创建数组,将正弦循环放入几个区间,如[0.0到0.1],[0.1到0.2],……并且应该有一个来自运算符的最大输入。之后,我应该计算每个区间的面积。

一切都很好,但是在第14次间隔之后,我的程序中断了,我不知道为什么..也许你能帮我,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ARR_MAX 1000

float f(float x) {
    float sinus = (float)sin((float)x);
    return(sinus);
}

float max(float a, float b) { 
    if (a < b)
        return(b);
    else
        return(a);
}


float min(float a, float b) { 
    if (a < b)
        return(a);
    else
        return(b);
} 

int main(void) {
    printf("Dieses Programm berechnet Ober und Untersummen einer Sinuskurve\n");    
    float x; int xmax; float result;
    int arr[ARR_MAX];
    printf("Geben Sie die Zahl xmax ein: "); // put in the max amount of numbers
    scanf("%d\n", & xmax); 
    if (ARR_MAX > xmax) {   
        xmax = xmax*10;             
        for (int i = 0; i <= xmax; i += 1) {    // here i create arrays for my intervals
            x = i;      
            arr[i] = i;
            x = x/10;

            float a = x - 0.1; 
//left interval is always 0.1 lower than variable for example you get x = 0.3 --> 0.3 - 0.1 = 0.2; so interval is a = 0.2, b = 0.3
            float b = x; 
            float T = 0.1; //accuracy

            float uppersum; 
            float lowersum;
            long numberintervals = 10; 

            do {                            

// i use this do while operation to get the result for each interval
                float lengthintervals = b/numberintervals; 
                uppersum = 0.0; 
                lowersum = 0.0; 
                int i; 
                for (i = 0; i < numberintervals;i++) { 
                    float x = a + i*lengthintervals; 
                    float y1 = f(x); 
                    float y2 = f(x + lengthintervals); 
                    float upperamount = max(y1, y2); 
                    float loweramount = min(y1, y2); 
                    uppersum += upperamount*lengthintervals; 
                    lowersum += loweramount*lengthintervals; 
                } 
            } while (uppersum - lowersum > T); 

            result = result + lowersum; 


            printf("arr[%d] = %f  -  ", arr[i], x);
            printf("Flächensumme = %f  -  ", lowersum); 
            printf("neues Ergebnis = %f\n", result);
        }
    } else {
        return EXIT_SUCCESS;        
    }

}

共1个答案

匿名用户

arr[i]中使用的i可以超出数组边界,因为i可以大于ARR_MAX

int arr[ARR_MAX];
...
if (ARR_MAX > xmax) {   
        xmax = xmax*10;             
        for (int i = 0; i <= xmax; i += 1) {
            ...      
            arr[i] = i;

相关问题