While never ends with random number - c

I am trying to get a random number and have the while end if its over another number:
int main() // random
{
int x= 50;
int i;
while (i>x){
srand(time(0));
int i = rand() %100;
printf("laenge %d", i);
}
}
The while starts well and generates different numbers (like 1.000 times 11, 1.000 times 75...) but it never ends.
I have 2 questions, why does it not end?
And why does it get in the console 1.000 times the same random number and then 1.000 times the next one?
If I add:
int main() // random
{
int x= 50;
int i;
while (i>x){
srand(time(0));
int i = rand() %100;
printf("laenge %d", i);
sleep(1);
}
}
Sleep(1); the whole code doesn't work anymore.

You redeclare i here:
int i = rand() %100;
^^^
so it is a different i then the one use to check the while loop here:
while (i>x){
this also means you need initialize i in the first declaration since using an uninitialized variable is undefined behavior.
You only should call srand once, so move it outside the loop. Also it would be a good idea to read How can I get random integers in a certain range? from the C FAQ. The recommended formula for generating a random integer in the range [M, N] is:
M + rand() / (RAND_MAX / (N - M + 1) + 1)
which in your case would be:
rand() / (RAND_MAX / (100 + 1) + 1)

You are seeding the random number generator inside the loop with the time in seconds as a seed. This resets the random number generator, so it will always return the same number until time(0) returns a different value (i.e., a second has passed). Move the seeding outside the loop.
Also remove the int from int i inside the loop, otherwise you will have a different i inside the loop than the one you are checking in the loop condition, which causes the loop to never end since the i in i > x is never changed.
And, finally, initialize i so that it will have a known value when the loop first starts. (Or change the loop to do-while so that the condition is at the end.)
int x = 50;
int i = 51; // <- initialize
srand(time(0)); // <- seed outside loop
while (i > x) {
i = rand() %100; // <- use the same 'i' inside and outside loop
printf("laenge %d", i);
}

Because you are seeding each time with almost the same number: time(0) will return the same number for about a thousand loops before being updated.
Solution: remove the srand(time(0)) from your loop and put it before the while().

Related

Why does my srand(time(NULL)) function generate the same number every time in c? [duplicate]

This question already has answers here:
Random numbers in C
(10 answers)
How can I generate different random numbers for each player?
(3 answers)
Closed 4 years ago.
So I was creating a program that would call a function and return 0 or 1 (0 meaning tails and 1 meaning heads) and then use that to print the outcome of 100 flips.
It seemed simple enough thinking I could use srand(time(NULL)) to seed rand() with constantly varying seeds. Here was my first crack.
#include <stdio.h>
#include <stdlib.h>
int flip();
int main(void) {
int heads = 0;
int tails = 0;
for (short int count = 1; count <= 100; ++count) {
int number = flip();
if (number == 0) {
printf("%s", "Tails");
++tails;
}
else if (number == 1) {
printf_s("%s", "Heads");
++heads;
}
}//end for
printf_s("\n%d Tails\n", tails);
printf_s("%d Heads", heads);
}//end main
int flip(void) {
srand(time(NULL));
int number = (int)rand();
printf("%d", number%2);
return number%2;
}//end flip
I would run the program and my rand() value would always be a five digit integer repeated in each iteration of the for statement (i.e 15367, 15745, or 15943).
I messed around until I discovered changing srand(time(NULL)) to srand(time(NULL)*time(NULL)/rand()) did the trick.
My only thought is that the time between each for iteration is so small the the time(NULL) part of the srand() function doesn't change enough to feed a different seed value.
I also tried srand(time(NULL)/rand()), however, this produced the same result (52 heads 48 tails) every time I ran the program (20+times); however, the rand() values were all different from each other.
I do not know why these things happened, or why the final srand(time(NULL)*time(NULL)/rand()) function worked, and I would love it if someone could explain!
The reason is, that time(NULL) changes only once per second!
This means, that you seed the random number generator 100 times with the same seed.
A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.
If you start your program more often than once a second, you could also seed it with
srand(time(NULL)+getpid());
or similar.

C runtime error during recursive function call

So I have a program to find the total number of ways in which an integer N can be expressed as the sum of "n" integers.
For example, 10 can be expressed as a combination of 2,3 and 5 as follows-
10 = 5 + 5
10 = 5 + 3 + 2
10 = 3 + 3 + 2 + 2
10 = 2 + 2 + 2 + 2 + 2
#include<stdio.h>
#include<stdlib.h>
int ways(int,int*,int);
int main() {
int n,num; //n is number of possible integers
scanf("%d",&n);
int*curr=(int*)malloc(n*sizeof(int)); //dynamically allocated array that stores all "n" integers in array form
for(int i=0;i<n;i++) {
scanf("%d",curr+i);
}
int t,N; //t is number of test cases
scanf("%d",&t);
while(t--) {
scanf("%d",&N); //for each test case, scans the number N that needs to be expressed as a sum of combinations those "n" integers
num=ways(N,curr,n);
printf("%d\n",num);
}
return 0;
}
int ways(int N,int*p,int size) {
int flag=1;
for(int i=0;i<size;i++) {
if(N/(*(p+i))!=0) {
flag=0;
break;
}
//Above loop says that if number N is less than all of the "n" integers, it
cannot be expressed as their sum. Hence, 0 will be returned if flag is 1
}
if(flag==1)
return 0;
if(N==0)
return 1;
int num=0,temp;
for(int i=0;i<size;i++) {
temp=*(p+i);
num=num+ways(N-temp,p,size); //GETTING RUNTIME ERROR AT THIS LINE
}
return num;
}
The program is getting SIGSEGV error at the recursive function call even for very small depth of recursion
In the first i loop in ways, you seem to be looking for a value in
array p that is smaller than N (though division is a horribly
inefficient way to test). Having found one, you do other things, then
use another i loop, losing the value of i you found in the first
one, and call ways recursively.
Now, note that you do no testing in the second loop. It’s entirely
possible to subtract something from N that is larger than N, get a
negative result, and pass that. This would cause infinite recursion, no?
A SIGSEGV error is a Segmentation fault error, which means that you are trying to access a memory location out of your programs reach.
This is most common due to de-referencing a null pointer or going over in your for loop. Try checking the logic of your code.
I think when you are typing *(p + 1), you are going out of bounds at some point. Try debugging with breakpoints or by outputting the value of *(p+1) in the for loop.

rand() returns nothing but zeroes

I am trying to write a program that will assign 5 random integers to an array but so far it is filling the array with zeroes. Also, the first number can't be a zero. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
int number[5];
int main() {
int i;
int t=0;
for (int t=0;t<5;t++) {
if (i=0)
{number[i] = rand()%8+1;}
else
{number[i] = rand()%10;}
i++;
printf("%d", number[i]);
}
return (0);
}
if (i=0)
That's assignment, not equality comparison.
int i;
Also, i is uninitialized, so accessing its value is undefined behavior. Since you accidentally assigned to it instead of comparing to it, if (i=0) doesn't invoke undefined behavior, but it would if you fixed the first bug.
i++;
printf("%d", number[i]);
Incrementing i before the print means you always print the cell right after the one you were working on.
You don't actually need i; t does everything you want i to do. We'll remove i and rename t to i:
for (int i = 0; i < 5; i++) {
if (i == 0) {
number[i] = rand() % 8 + 1;
} else {
number[i] = rand() % 10;
}
printf("%d", number[i]);
}
Several things are wrong in your code ...
1)
You didn't initialize the variable i
2)
if(i=0)
should be
if( i == 0 )
3)
You can use variable t instead of i -- means variable i is unnecessary
4)
You should have a function call for randomize() function before rand() function call, so that you can get the real random numbers
5)
If you just want to show the random numbers, you don't even need to use array
You will get the same sequence of 'pseudo-random' values by calling rand() in your program. To change this sequence the Random Number generator has to be 'seeded'. This is done by calling srand() function once with a seed value at the beginning of your program.
Ideally the value used for seed should change with each run of the program. Things that you could use as the seed are the process id, time, date or any other system provided value that is guaranteed to be different for each run of the program.
void srand(unsigned int seed);
Apart from that there are logical flaws in your program as others have highlighted, of which the if conditional assignment error is the most serious.

How to get a random number every time a function is called in C

So I'm making a game that needs to generate a random number every time the attack function is called. For every run of the program it generates a a different one, I think this is because I use srand(time(NULL)); however, if I attack more than once, the it returns the same number that I already called. Here is a sample of my random function at the moment.
srand(time(NULL));
int attrand = rand() % 16;
How can I make it return a different number every time it is called within the same execution of the program?
Move the seed initialization to some init function, and keep only int attrand = rand() % 16; in this function.
void my_init() {
srand(time(NULL));
}
int get_random() {
return rand() % 16;
}

Compound conditions using while loop in C.

The program is ignoring Stop when amt is 0 until after 10 numbers have been entered. The program also doesn't stop after 10 numbers have been entered. Where is my error?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
Your test is happening before amt is assigned. Thus its results are undefined. This test should be moved to the end of the iteration, i.e. a do/while. Whilst you could assign amt to some non-zero value this feels slightly untidy to me.
And surely you mean to use logical AND rather than logical OR? You only want to continue iterating if both amt is non-zero AND i<10.
Of course, if you did move the test to the end of the iteration then you would have to account for the fact that i had been incremented inside the loop.
In order to stop after 10 numbers or amt=0 (whichever first is met) you'll have to change the loop condition to while (amt!=0 && i < 10)
int amt;
Since you do not initialize it. It has some random value and that causes the Undefined Behavior in your program.
You should always initialize local variables with values.

Resources