-
qsort
the program gets 6 random numbers. i've been trying to use the qsort function to print them in ascending order.
it seems to be printing the location in memory where they are stored rather than the numbers themselves..
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //for seeding randomiser
#define MAX 6
int rnd(int range);
void seedrnd(void);
int intcmp(const void *v1, const void *v2);
int main()
{
int x;
int results[MAX];
seedrnd(); //prepare random-number gen.
//display 6 random numbers
printf("Here are your six National Lottery numbers:\n\n");
while (x<6)
{
results[0]=rand();
{
results[0]++;
}
}
qsort(results, MAX, sizeof(results[0]), intcmp);
for (x=0;x<6;x++)
printf("\nresults[%d]", &results[x]);
system("PAUSE");
return 0;
}
int rnd(int range)
{
int r;
r=(rand()%range)+1; //random numbers
return(r);
}
void seedrnd(void) //seed the random number
{
srand((unsigned)time(NULL));
}
int intcmp(const void *v1, const void *v2)
{
return(*(int *)v1- *(int *)v2);
}
-
> it seems to be printing the location in memory where they are stored rather than the numbers themselves..
Because that's what you asked it to do
>printf("\nresults[%d]", &results[x]);
Try
printf("\nresults[%d]", results[x]);
-
ok thanks i see that now...
now i have the problem that the numbers generated are far too high..how can i edit the code so that the random numbers stay below 49?
-
Try this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //for seeding randomiser
#define MAX 6
int rnd(int range);
void seedrnd(void);
int intcmp(const void *v1, const void *v2);
int main()
{
int x;
int results[MAX];
seedrnd(); //prepare random-number gen.
//display 6 random numbers
printf("Here are your six National Lottery numbers:\n\n");
for (x=0; x<6; x++)
{
//Generates number from 1 to 48
results[x]=(rand() % 48) + 1;
}
qsort(results, MAX, sizeof(results[0]), intcmp);
for (x=0;x<6;x++)
printf("results[%d]\n", results[x]);
system("PAUSE");
return 0;
}
int rnd(int range)
{
int r;
r=(rand()%range)+1; //random numbers
return(r);
}
void seedrnd(void) //seed the random number
{
srand((unsigned)time(NULL));
}
int intcmp(const void *v1, const void *v2)
{
return(*(int *)v1- *(int *)v2);
}
-
thanks, that worked perfect :)