-
Median in array
I have this programm where u put in an amound of numbers and the program calculates the median. But when i give in any number it says acces violation error?
i can't figure out the problem
Code:
/* INCLUDES: */#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
/*DECLARATIONS*/
int nGem(int);
/* MAIN PROGRAM: */
int main(void)
{
int n;
int nAantal;
int nB;
int nInvoer;
int nArray[20]={1};
printf("Hoeveel weerstanden wilt u invoeren?");
scanf("%d", &nAantal);
for (nB = 0; nB<nAantal; nB++)
{
printf("Voer een aantal weerstanden in");
scanf("%d", nArray[nB]);
}
n = nGem(nInvoer);
printf("%d", &n);
return(0);
}
int nGem(int nInvoer)
{
char chAgain = 'y';
int nAantal;
int nSum = 0;
int nAverage = 0;
int nB;
int nU ;
int nArray[100] = {1};
for (int i = 0; i < 10; ++i)
{
nSum+=nArray[i];
}
nAverage = nSum/10;
return nAverage;
}
-
Code:
printf("Voer een aantal weerstanden in");
scanf("%d", nArray[nB]);
}
You missed the & there. array[X] gives you the value of spot X in array. If you want the address of that spot (and scanf does expect addresses as arguments), then you need to supply that.
Quzah.
-
Thnx for the help:P
Okay, works for me, but there is a thing left. Any values i enter he calculates the same median: 1245008. I get that answer with any value i enter. Weird
-
Code:
int nInvoer; /* what value does this have? */
int nArray[20]={1};
printf("Hoeveel weerstanden wilt u invoeren?");
scanf("%d", &nAantal);
for (nB = 0; nB<nAantal; nB++)
{
printf("Voer een aantal weerstanden in");
scanf("%d", nArray[nB]);
}
n = nGem(nInvoer); /* what value are you passing to this function? */
Now your function doesn't actually even use its argument, so you don't need to be passing it anything (even though you're passing it the wrong thing). This though is another problem:
Quzah.
-
Make sure you do a check here for the number received so you don't go out of your array's boundary.
Code:
int nArray[20]={1};
printf("Hoeveel weerstanden wilt u invoeren?");
scanf("%d", &nAantal);
for (nB = 0; nB<nAantal; nB++)
{
printf("Voer een aantal weerstanden in");
scanf("%d", &nArray[nB]);
}