我必须编写一个程序来计算正弦循环。第一个任务是创建数组,将正弦循环放入几个区间,如[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;
}
}
答案 0 :(得分:1)
i
中使用的arr[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;