As per the heading really the code for saving the data to a file seems to work fine as the program runs and the file exists. However in the second part of code the program compiles but stops with error when running. Before I post code wanted to say thanks to the posters as I have learned a lot from this site but is my first time posting.
#include <stdio.h>
#include <stdlib.h>
int const MAX_SIZE = 1000000;
FILE *randomdata;
char outputFilename[] = "array.dat";
int main(void)
{
int i;
randomdata = fopen(outputFilename, "w");
for (i = 0; i < MAX_SIZE; i++)
fprintf(randomdata, "%lf\n", rand() * 1.0 / RAND_MAX);
return 0;
}
As can be seen the first piece of code makes a file called array.dat which stores random numbers.
The second piece where I assume there is a logic error somewhere is meant to take in the numbers from array.dat and then figure out the median value.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000000
#include <time.h>
int main(void)
{
int left, right;
int pivot_index, store_index;
int i, k;
double tmp;
double a[MAX_SIZE];
double pivot_value;
double start;
double end;
FILE *f;
char inputFilename[] = "array.dat";
for (i = 0; i < MAX_SIZE; i++) {
f = fopen("array.dat", "r");
fscanf(f,"%lf", &a[i]);
printf("%lf", &a[i]);
}
k = MAX_SIZE / 2; /* the median position */
left = 0; right = MAX_SIZE;
start = clock();
srand(time(0));
while (left != k) {
pivot_index = rand() % (right -left) + left;
pivot_value = a[pivot_index]; /* swap (a[ pivot_index ],a[ right -1]) ; */
tmp = a[pivot_index];
a[pivot_index] = a[right - 1];
a[right - 1] = tmp;
store_index = left;
for (i = left; i < right - 1; i++) {
if (a[i] < pivot_value) { /* swap (a[ store_index ], a[i ]) ; */
tmp = a[store_index];
a[store_index] = a[i];
a[i] = tmp;
store_index++;
}
} /* swap (a[ right -1] , a[ store_index ]) ; */
tmp = a[right - 1];
a[right - 1] = a[store_index];
a[store_index] = tmp;
pivot_index = store_index;
if (k <= pivot_index) {
right = pivot_index;
} else {
left = pivot_index + 1;
}
}
end = clock();
printf("The program took %lf seconds\n", endstart / 1000000);
printf("Median is %lf\n", a[k - 1]);
return 0;
}
The problem in the code definitely comes somewhere around the following part I think:
for (i = 0; i < MAX_SIZE; i++) {
f = fopen("array.dat", "r");
fscanf(f,"%lf", &a[i]);
printf ("%lf", &a[i]);
}
there are three things you must know about while using FILE in read mode in c . 1) open the file first by fopen(); 2) check whether the file is open or not. 3)close the file by fclose().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.