Click to See Complete Forum and Search --> : 2 Simple C Questions
Charred_Phoenix
12-11-2002, 09:12 PM
1. How can i program tcp/ip apps in C, do i need a new library or is one already provided? if so then what are the commands and which library is this.
2. How can i generate random numbers, i have tried random(<number here>);
but it just generates the same number over and over again -_-'
anyway thanks ^_^
Spawn913
12-11-2002, 10:50 PM
1) use the sockets library.
> man socket
2) it's been a while since I had to generate random numbers, but it should be something like:
/* initialize a seed value */
srand(<seed value, usually the time to make this more random>);
/* generate an int from 1 to 10 */
randomnum=1+(int)(10.0*rand()/(RAND_MAX+1.0))
You can also do away with the srand() line since the period of rand() is rather large, so the posibility of getting the same sequence is not that big.
By the way, I don't think random() has any parameter. It's prototype is:
long int random (void);
Are you sure you didn't get any error?
:cool:
Charred_Phoenix
12-11-2002, 11:11 PM
It compiled fine, but like i said it just generate the same thing over and over :|
thanks for your help!
Charred_Phoenix
12-11-2002, 11:20 PM
[Charred@cpe-144-132-227-113 C]$ cat stabhim.c
#include <stdio.h>
int main(void) {
int carcle;
carcle = 1+(int)(10.0*rand()/102+1.0);
printf("%d\n", carcle);
return 0;
}
[Charred@cpe-144-132-227-113 C]$ gcc -o gunner stabhim.c
[Charred@cpe-144-132-227-113 C]$ ./gunner
176891117
[Charred@cpe-144-132-227-113 C]$ ./gunner
176891117
[Charred@cpe-144-132-227-113 C]$ ./gunner
176891117
[Charred@cpe-144-132-227-113 C]$
:'(
Spawn913
12-11-2002, 11:34 PM
#include <stdio.h>
#include <stdlib.h> /* for the rand() function */
#include <time.h> /* to generate a seed based on time */
int main(void)
{
int carcle;
srand(time(NULL)); /* set seed to current time */
//carcle = 1+(int)(10.0*rand()/102+1.0);
carcle = 1+(int)(10.0*rand()/RAND_MAX+1.0); /* RAND_MAX is a constant */
printf("%d\n", carcle);
return 0;
}
Charred_Phoenix
12-11-2002, 11:40 PM
Sorry.... i'm an idiot -_-
Charred_Phoenix
12-12-2002, 12:10 AM
Heh... if this is the way it works then rand is a pretty useless function... i mean all its doing is performing a calculation that is the same each time, it only changes cos the seed changes, blah
Spawn913
12-12-2002, 12:24 AM
well.. not really. two successive calls to rand() would give different values:
...
srand(seed);
random1=rand();
random2=rand();
....
in the above, random1 != random2
the reason I had to place an srand() at the code is because you only call rand() once -- thereby generating the same value each time the program is run. If your program needs to repeatedly generate random numbers, then you can be sure that rand() would generate "random" values.
Charred_Phoenix
12-12-2002, 12:59 AM
Thanks once again, sorry for making you return to this thread again and again