Description: Calculates the integral between 0 and a user defined limit.
Problem: I can't seem to get the validation of temp to work.
cos2.dat:
Code:
0.000000 1.000000
0.000157 1.000000
0.000314 1.000000
0.000471 1.000000
0.000628 1.000000
0.000785 0.999999
0.000942 0.999999
0.001100 0.999999
a 0.999998 // test fail point.
0.001414 0.999998
0.001571 0.999998
0.001728 0.999997
0.001885 0.999996
0.002042 0.999996
....
Program:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define max_limit 1.570639
#define limitcheck(x) ((x < 0)||(x > max_limit) ? -1 : x)
/* Function prototype */
double integral(double x[], double f[], int N, double *a, double *b);
int main(int argc, char* argv[])
{
FILE *input;
int i=0, N=0, v1=0, v2=0;
double a=0, b=0, valid[1], temp, dump, *x, *f, m;
const char inp_fn[]="cos2.dat";
char test;
if(argc != 2) // Check input.
{
printf("You have failed to provide the integration limit\n");
exit(EXIT_FAILURE);
}
else // Read input.
{
valid[0]=sscanf(argv[1], "%lf", &b);
b = limitcheck(b); // Check the limit is within range.
/* Open input file */
input = fopen(inp_fn, "r");
if(!valid[0]) // Invalid input.
{
printf("You have failed to provide a valid integration limit.\n");
exit(EXIT_FAILURE);
}
else if(b < 0) // Invalid range.
{
m = max_limit;
printf("Please enter integration limit between 0 and %lg.\n", m);
exit(EXIT_FAILURE);
}
else if(input == (FILE*) NULL) // No file.
{
printf("Input file could not be opened (cos2.dat).\n");
exit(EXIT_FAILURE);
}
else // Valid.
{
for(N=0; (b>temp); N++)
{
fscanf(input, "%lf", &temp);
fscanf(input, "%lf", &dump);
if( isalpha(temp) )
{
printf("Input file was corrupted (cos2.dat).\n");
exit(EXIT_FAILURE);
}
}
rewind(input); // Reset to begining of file.
x = malloc((N)*sizeof(double)); // Allocated memory for x.
f = malloc((N)*sizeof(double)); // Allocated memory for f.
for(i=0; i<(N-1); i++) // Inputing array values.
{
fscanf(input, "%lf", &x[i]);
fscanf(input, "%lf", &f[i]);
}
/* Close input file */
fclose(input);
integral(x,f,N,&a,&b);
free(x); // Clearing memory
free(f); // Clearing memory
exit(EXIT_SUCCESS);
}
}
return(0);
}
double integral(double x[], double f[], int N, double *a, double *b)
{
int j=1;
double sum=0, h=0;
/* Calculating integral */
for (j=1; j <= (N-2); j= j+1)
{
sum += f[j-1]*(x[j]-x[j-1]);
h = (x[j]-x[j-1]);
}
sum += f[j-1]*(*b-x[j-1]); // Adding final term.
printf("Integral of cos^2 between %lf and %lf = %lf\n", *a, *b, sum); // Output
}