In: Computer Science
#include <stdio.h>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#pragma warning (disable : 4996)
int main() {
const char* filename = "samples.coe";
const int N = 1024;
FILE* file = fopen(filename, "w");
if (file == NULL) {
perror("fopen");
}
fprintf(file, "; These are 1024 sample values in range -1 to
1,\n");
fprintf(file, "; Sine Wave 0\n");
fprintf(file, "memory_initialization_radix = 10;\n");
fprintf(file, "memory_initialization_vector\n");
double values[N];
double delta = M_PI / (N - 1);
for (int i = 0; i < N; i++) {
if (i == 0) {
values[i] = 0.0;
}
else {
values[i] = values[i - 1] + delta;
}
}
double sin_values[N];
for (int i = 0; i < N; i++) {
sin_values[i] = sin(values[i]);
if (i != N - 1)
fprintf(file, "%f;\n", sin_values[i]);
else
fprintf(file, "%f\n", sin_values[i]);
}
fclose(file);
file = fopen(filename, "r");
char line[256];
int line_no = 0;
double max = 0.0000;
double min = 1.0000;
double total = 0.0;
while (fgets(line, sizeof(line), file)) {
line_no++;
if (line_no >= 4) {
double val;
scanf_s(line, "%lf;", &val);
if (val > max) {
max = val;
}
if (val < min) {
min = val;
}
total += val;
}
}
printf("max = %lf min = %lf mean = %lf", max, min, total / N);
}
why it doesn't work in visual studio?
could you fix the errors?
#include <stdio.h>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#pragma warning (disable : 4996)
#include<cstdio>
int main() {
const char* filename = "samples.coe";
const int N = 1024;
FILE* file = fopen(filename, "w");
if (file == NULL) {
perror("fopen");
}
fprintf(file, "; These are 1024 sample values in range -1 to 1,\n");
fprintf(file, "; Sine Wave 0\n");
fprintf(file, "memory_initialization_radix = 10;\n");
fprintf(file, "memory_initialization_vector\n");
double values[N];
double delta = M_PI / (N - 1);
for (int i = 0; i < N; i++) {
if (i == 0) {
values[i] = 0.0;
}
else {
values[i] = values[i - 1] + delta;
}
}
double sin_values[N];
for (int i = 0; i < N; i++) {
sin_values[i] = sin(values[i]);
if (i != N - 1)
fprintf(file, "%f;\n", sin_values[i]);
else
fprintf(file, "%f\n", sin_values[i]);
}
fclose(file);
file = fopen(filename, "r");
char line[256];
int line_no = 0;
double max = 0.0000;
double min = 1.0000;
double total = 0.0;
while (fgets(line, sizeof(line), file)) {
line_no++;
if (line_no >= 4) {
double val;
std::sscanf(line, "%lf;", &val);
if (val > max) {
max = val;
}
if (val < min) {
min = val;
}
total += val;
}
}
printf("max = %lf min = %lf mean = %lf", max, min, total / N);
}
The compiler of your visual studio does not compile line57: scanf_s(line, "%lf;", &val); You have used <stdio.h> which is the header of scanf_s and still error is thrown.That is because your compiler is not aware of scanf_s.
So try using scanf or std::sscanf with header #include<cstdio> instead of scanf_s.
I have attached the program by using std::sscanf for your reference. Hope this code works on your compiler.