This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 7 years ago.
I am new in programming. I need something which can generate random number with C. I found "rand()". But it is not generating random values. Please check the following simple code.
The following code gives
roll the first dice : 6
roll the second dice : 6
roll the third dice : 5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int dice1,dice2,dice3,total1,total2;
char prediction[10];
int dice_generator()
{
dice1= (rand()%6)+1;
printf("roll the first dice: %d \n", dice1);
dice2= (rand()%6)+1;
printf("roll the second dice: %d \n", dice2);
dice3= (rand()%6)+1;
printf("roll the third dice: %d \n", dice3);
return 0;
}
dice_generator();
total1 = dice1+dice2+dice3;
printf("final value is = %d\n",total1);
return 0;
}
You need to "seed" the random number generator.
Try calling
srand(time(NULL));
once at the top of your program.
(There are better ways, but this should get you started.)
Firstly, C language does not support nested functions. It is illegal to define dice_generator() inside the definition of main() as in your code. Your compiler might support this, but in any case this is not C.
Secondly, rand() does not generate random numbers. rand() produces a seemingly "erratic" but perfectly deterministic sequence of integers, which begins at some initial number and always follows the same path. All you can do is make rand() start its sequence from a different "seed" number by calling srand with a new seed as an argument.
By default rand() is required to work as if you called srand(1) in order to seed the sequence.
here is the code, after being corrected so the sub function dice_generator()
is properly separated, rather than buried in main().
(in C, nested functions are not allowed)
the rand() function is properly initialized via the srand() function.
unused variables ( total2 and prediction[] ) are commented out
(another excellent reason to only place one variable declaration per line)
Strongly suggest enabling all the warnings when compiling,
so your compiler can tell you about problems in the code.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
// prototypes
int dice_generator( void );
// global data
int dice1;
int dice2;
int dice3;
int total1;
//int total2;
//char prediction[10];
int main( void )
{
srand(time( NULL ));
dice_generator();
total1 = dice1+dice2+dice3;
printf("final value is = %d\n",total1);
return 0;
} // end function: main
int dice_generator()
{
dice1= (rand()%6)+1;
printf("roll the first dice: %d \n", dice1);
dice2= (rand()%6)+1;
printf("roll the second dice: %d \n", dice2);
dice3= (rand()%6)+1;
printf("roll the third dice: %d \n", dice3);
return 0;
} // end function: dice_generator
Related
This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 7 years ago.
This is my code:
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main(){
float m, n;
printf("Enter n, m:");
scanf("%f %f", &n, &m);
int l;
l=m-n;
int i;
for(i=0; i<4; i++){
srand(time(NULL));
double r=rand();
r/=RAND_MAX;
r*=l;
r+=n;
printf("%f ", r);
}
return 0;
}
Why it generates same numbers? and when I write srand(time(NULL));before the loop it generates different numbers! why it is like this? how does this program work?
srand() seeds the random number sequence.
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. ... C11dr §7.22.2.2 2
And time() is typically the same value - for a second #kaylum
[Edit]
Better to call srand() only once early in the code
int main(void) {
srand((unsigned) time(NULL));
...
or, if you want the same sequence every time, do not call srand() at all - useful for debugging.
int main(void) {
// If code is not debugging, then seed the random number generator.
#ifdef NDEBUG
srand((unsigned) time(NULL));
#endif
...
The call to time(NULL) returns the current calendar time (seconds since Jan 1, 1970).
So its the same seed you are giving. So, rand gives the same value.
Simply you may use:
srand (time(NULL)+i);
This is my first C program and I wanted to make a random password, but every time I run the program, it generates the same string. (always generates "pkDHTxmMR1...") This is not going to actually be used so the security of rand() doesn't really matter to me. Why would it output the same string every time that I run it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//this is a program to generate a random password
int main()
{
int counter = 0;
srand(time(NULL));
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
//seed random based on time
srand(time(NULL));
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
return 0;
}
Oh dear. Everybody has got the answer wrong, including me before I tried the questioner's code for myself.
In fact, yes there should be no call to srand() in the loop because it will reseed the random number generator on each iteration. However, there should also be no call to srand() outside the loop either because the function used to generate actual random numbers is random() not rand(). The correct code is
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int counter = 0;
srandom(time(NULL)); // Correct seeding function for random()
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
printf("\n"); // Stops the output from being on the same line as the prompt
return 0;
}
Your loop takes less than a second to run.
Therefore, time(NULL) always returns the same value, so your random numbers all have the same seed.
Don't do that.
The standard:
The srand function uses the argument as a seed for a new sequence of
pseudo-random numbers to be returned by subsequent calls to rand. If
srand is then called with the same seed value, the sequence of
pseudo-random numbers shall be repeated.
It is very likely that the time_t on your system is based on seconds or something like that. But the execution time between srand() calls is far far less than one second, so you keep feeding it the same seed value.
Always just call srand() once in your whole program.
This question already has answers here:
rand() not generating random numbers after modulo operation
(8 answers)
Closed 7 years ago.
I got this code:
#include <stdio.h>
#include <conio.h>
int rand();
int main()
{
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
The function to generate random numbers generate the same numbers in every execution, how do I fix that?
You need to initalise your rand() with srand() like so :
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
In short, you need to feed your random some seeds so it can do his work, but you want to give him new seeds at each run, thus the use of time(NULL).
Oh, and also, you don't need to declare int rand(); before your main, but instead add <stdlib.h> to your list of includes.
Keep up the learning !
You have to set a seed so just do this before your while loop (Also don't forget to include: time.h):
srand(time(NULL));
You can generate different random numbers by using
#include <stdlib.h> // for rand() and srand()
#include <time.h> // for time()
// other headers
int main()
{
srand(time(NULL));
// rest of your code
}
By using srand(), you can seed the Random Number generator to get different random numbers on different runs of the program.
And also remove int rand(); from your code, unless you are trying to create your own rand() function
Seet seed or srand(time(NULL));
If u set with time, include <time.h> library.
I recomended you include <stdlib.h> - this is for srand or rand function.
I am trying to find the cube of the numbers from 1 to 10 using various types of for loops. I was wondering why after my for loop evaluates, the program stops and does not go on to evaluate the while loop? Can someone help? The for loop and while loop are supposed to do the same thing by the way. Thanks.
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(void)
{
int num;
for ( num=1; num<11; num++){
printf("The cube of %d is %d\n", num, num*num*num);
}
getchar();
return 0;
}
#include <stdio.h>
int main1(void)
{
int num1;
scanf("%d", &num1);
while (num1<11) {
printf("The cube of %d is %d\n", num1, num1*num1*num1);
num1++;
}
getchar();
return 0;
}
PS My first programming language is Python, so I am confused why C stop after the first for loop...
:(
main() and main1() are two different functions. Your system calls main(), the entry point of your program. When main() ends, that is when your program terminates. main1 isn't touched at all.
Either concatenate the two functions (copy-paste main1 into main) or call main1() from main(). But you would need a forward-declaration first:
int main1(void);
int main(void)
{
// ...
main1();
}
int main1(void) { ... }
BTW, main1 isn't a really good name for a function since it resembles main. That can confuse people who maintain your code.
after declaring num and num1 you set num in the for loop to 1, but not num1 in the while loop. plus the main functions issues mentioned
I have this problem with this homework I'm supposed to do.
[ It says Create a program that's able to calculate and show the sum of S]
Like S=1+1/4+1/8+1/16 ... till 1/ [2 pow n]
So I worked on it and came up with this code
#include <stdio.h>
void main()
{
int n,i;
float p,s;
printf("Enter the maximum power n :");
scanf("%d",&n);
s=0;
p=0;
for (i=0;i<n;i++)
{
p+=1/pow(2, i);
s+=p;
printf("s = %f\n",s);
}
printf("The sum of this equation is :%f",&s);
}
But when I execute it is always like S=0.
What am I doing wrong?
You are printing an address ('&s) with%f` variable. Using a wrong specifier invokes undefined behavior. You may get anything.
Also, No need of variable s. Remove the line
s+=p;
It should be like:
#include <stdio.h>
int main(void)
{
int n,i;
float p;
printf("Enter the maximum power n :");
scanf("%d",&n);
p=0;
for (i=0;i<n;i++)
{
p+=1/pow(2, i);
printf("p = %f\n",p);
}
printf("The sum of this equation is :%f",p);
}
You need to include <math.h> to get the proper prototype of pow().
You might need to link to the math library too gcc main.c -Wall -lm
#include <math.h>
....
for (i=0;i<n;i++)
{
p=1/pow(2, i);
s+=p;
printf("s = %f\n",s);
}
printf("The sum of this equation is :%f",s);
Your program has multiple problems. Enabling compiler warnings should tell you about some of them.
You should include the C header which contains the declaration of the pow function.
You add each addend twice.
In your second printf statement, you pass a float. But the %f format specifier expects a double argument. In your third printf statement, you pass a pointer to a float.
Another cosmetic problem is that your main function should return an int.
just a guess, may you replace the line
p+=1/pow(2, i);
with
p+=1.0f/(float)pow(2, i);
and
printf("The sum of this equation is :%f",&s);
with
printf("The sum of this equation is :%f",s);
Typo may be.. but you will have say %f and s (not &s)
printf("The sum of this equation is :%f",s);
On side note:
Once you include <math.h> you will get compiler warning for using correct pow(..) prototype. Below code would be relevant.
p+=1.0f/(float)pow(2.0f, i);