rand() keeps returning 0 - c

I am using Visual Studio 2010 and programming in C. I am attempting to produce a random integer value via the rand() method. Here is the code:
/*main.cpp*/
int main (void)
{
InitBuilding();
return 0;
}
/*building.cpp*/
//includes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//data structure
typedef struct
{
int type; //building type
} BUILDING;
//global variables
BUILDING g_aBld[200];
//initialization
void InitBuilding(void)
{
srand((unsigned)time(NULL));
for(int cntBld = 0; cntBld < 200; cntBld++)
{
g_aBld[cntBld].type = (rand() % 3);
}
}
After debugging I've realized that 0 is continually generated for each iteration of the loop. I've used this exact code before in other programs, and it worked fine. I have no idea why it wouldn't be working now.
Thanks in advance for any replies.

g_aBld[cntBld].type = (rand() % 3);
Don't use mod to reduce the range of rand because this can interoperate badly with the way your random number generator initializes itself. Try, for example:
g_aBld[cntBld].type = rand() / (RAND_MAX / 3);

Project compiled with the addition of
int main( int argc, char ** argv )
{
InitBuilding();
}
With this added the code worked producing types of 0, 1, 2

Related

Getting different answer on Windows vs Linux

I'm trying to solve this problem https://www.hackerrank.com/challenges/flowers
When I run my code in Visual Studio 2013 on Windows 7 on my machine I get the correct answers but on the site (I'm pretty sure they use Linux and I'm positive this is the compiler they use gcc 4.9.2, C99 standard) I get very large numbers for answers, specifically 12588576 (instead of 13) for the first test case and 1395920336 (instead of 15) for the second test case. I'm guessing it has something to do with the qsort call.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int comp_desc(const void * a, const void * b)
{
int * aPtr = (int*)a;
int * bPtr = (int*)b;
return *bPtr - *aPtr;
}
int main()
{
int flowersNeeded, numFriends, i;
scanf("%d %d", &flowersNeeded, &numFriends);
getchar();
int flowerCosts[100];
memset(flowerCosts, 0, 100);
for (i = 0; i < flowersNeeded; ++i)
{
scanf("%d", &flowerCosts[i]);
}
qsort(flowerCosts, 100, sizeof(int), comp_desc);
int flowersBought = 0;
int moneySpent = 0;
int multiplier = 1;
for (i = 0; i < flowersNeeded; ++i)
{
moneySpent += flowerCosts[i] * multiplier;
multiplier = (++flowersBought / numFriends) + 1;
}
printf("%d\n", moneySpent);
return 0;
}
memset(flowerCosts, 0, 100);
The 100 should be sizeof(flowerCosts). The 100 doesn't fill the whole array because it's the size in bytes.
qsort(flowerCosts, 100, sizeof(int), comp_desc);
You probably want to sort only the entries you filled in (flowersNeeded) rather than all 100 of them.
As a result of these two bugs, you're sorting garbage values in the uninitialized part of your array.

How to create a matrix with random numbers using typedef struct?

I'm trying to write a function that creates a matrix with ones and zeroes which are randomly distributed, but I'm getting an error: expected identifier before numeric constant.
Can someone can give me some pointers on what I'm doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 7
#define COLUMNS 7
typedef struct {
const int rows;
const int columns;
int board[ROWS][COLUMNS];
} game;
void newGame(game *session);
int main(void){
game session = {ROWS, COLUMNS};
srand(time(NULL));
return 0;
}
/* Function: newGame
* Description: Set up a new game with random states for each brick.
* Input: A pointer to the game structure.
* Output: The game structure pointed to is updated.
*/
void newGame(game *session){
for(int r = 0; r<ROWS; r++){
for(int c = 0; c<COLUMNS; c++){
session[r].ROWS = rand()%2;
session[c].COLUMNS = rand()%2;
}
}
}
This:
session[r].ROWS = rand()%2;
doesn't make any sense, session is a pointer to a single game, not an array, and ROWS is a #define that will be replaced by an integer here.
You probably meant:
session->board[r][c] = rand() % 2;
Also you are handling the size rather confusingly, it's both constant and run-time readable. I'm not sure that makes total sense to me, but perhaps it's handy for some reason.

Beginner Here Rand in c

im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.

Random number in for loop C

I need to generate 1000 random numbers inside a for loop.
my problem is that the random number generated is always the same. since im using time NULL to initiate the generator, why am i getting the same numbers? here is the code i used:
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i = 0; i < 1000; i++){
int x = rand() % LIMIT;
printf("%d\n", x);
}
}
If you run the program multiple times during the same second, you will pass the same value to the generator as seed. You have to wait at least a second before trying it again.
This is because the time function returns the number of seconds since a specific time, and if called multiple times during the same second will return the same value.
your code is right, but you forgot to include the time.h library.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // <--- now it works
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i=0;i<1000;i++){
int x = rand() % LIMIT;
printf("%d",x);}

c random number on time

Why does this program only generate numbers from 0.1-0.2. It needs to generate numbers from 0-1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
/*declare pseudo-random number */
float random;
srand(time(NULL));
random = (float) rand() / (float) RAND_MAX;
printf("The random number is %f\n", random);
return 0;
}
I'm compiling using gcc on a mac.
The code seems fine to me. Try to generate more than one number and see then:
for(i=1; i<100; i++){
random = (float) rand() / (float) RAND_MAX;
printf("%f\n", random);
}
int random_seed;
void __cdecl srand(int data){
random_seed = data;
}
int __cdecl rand (
void
)
{
return( ((random_seed = random_seed * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
This is the implementation of srand() and rand() on windows CRT. I am not sure if I will be sued by MS for this.
Clearly, you might have to call rand() many times to get a proper value between 0 and 1. no matter what time() returns[as it will only be set into random_seed].
The above code went fine for me(gcc in ubuntu) i.e. my output was varying from 0.1 to 1. Try to run the program three-four times an then see the output

Resources