For some reason I was getting a dramatically incorrect answer for a problem, so I put in this printf to try and debug.
for (s = 0; s <= 100; s++) {
for (t = 0; t <= 100; t++) {
printf("At (%f,%f), spl = %f\n", s, t, spl(loc_data, s, t)); */
if (spl(loc_data, s, t) > 80) {
p++;
}
}
}
If I omit the printf line, I get an incorrect answer. I think that it has something to do with memory allocation or uninitialised variables, but this is beyond my abilities. Any help would be appreciated.
Whole code:
#include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
double W;
} data_t;
double spl(data_t *, double, double);
int main(int argc, char **argv) {
data_t loc_data[1000];
double spl0, p = 0, pp;
int i = 0, j = 0;
double s, t;
while (scanf("%lf %lf %lf", &loc_data[i].x, &loc_data[i].y, &loc_data[i].W) == 3) {
i++;
}
printf("\nStage 1\n=======\n");
printf("Number of sound sources: %d\n", i);
for (j = 0; j < i; j++) {
printf("%.1f meters east, %.1f meters north, power %1.5f Watts\n",
loc_data[j].x, loc_data[j].y, loc_data[j].W);
}
printf("\nStage 2\n=======\n");
spl0 = spl(loc_data, 0, 0);
printf("SPL at (0.0,0.0): %.1f dB\n", spl0);
printf("\nStage 3\n=======\n");
for (s = 0; s <= 100; s++) {
for (t = 0; t <= 100; t++) {
printf("At (%f,%f), spl = %f\n", s, t, spl(loc_data, s, t));
if (spl(loc_data, s, t) > 80) {
p++;
}
}
}
pp = p / 102.01;
printf("Points sampled: 10201\nAbove 80.0 dB: %.1f%%\n", pp);
return 0;
}
double spl(data_t *loc_data, double pointx, double pointy) {
int i = 0;
double r_sq, powi, spli, spl;
while (loc_data[i].W != 0) {
r_sq = pow(loc_data[i].x - pointx,2) + pow(loc_data[i].y - pointy,2);
powi = 10*log10(loc_data[i].W / pow(10,-12));
spli = powi + 10*log10((2 / (4 * M_PI * r_sq)) + (4 / (2.5 * M_PI * r_sq)));
spl = 10*log10(pow(10, spl/10) + pow(10, spli/10));
i++;
}
return spl;
}
Apologies for the poor formatting.
You”re using a variable (
spl) before it’s initialized inthe functionspl():Calling
printf()is probably influencing the value the variable happens to have.Also, you read in a number of entries into the
loc_dataarray, but don’t pass that information to thespl()function. Inspl()you treat the array entry with fieldWas the ‘sentinel’ – the end of the array. Is it a given that the last entry in the input data will have a zero value? If so, you should probably let us know, and probably check for that when done reading the input.