My rand() function didn't work - c

this is my function: i need that every number that get random will be: one bigger than 50, one even, and one not even. i complied just with gcc and i'm using c99. It compiled well, but it when it print three random numbers it's print 0,0,and real random number. I want it to print for me three real numbers. thanks for who trying to help!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_NUMBER 100
int isValidNumbers(int num1,int num2, int num3);
int main(void)
{
srand (time(NULL));
int num1 = 0;
int num2 = 0;
int num3 = 0;
num1,num2,num3 =isValidNumbers(num1,num2,num3);
printf("%d %d %d\n",num1,num2,num3);
system("PAUSE");
return 0;
}
int isValidNumbers(int num1,int num2, int num3)
{
int i=1,ans = 0;
do
{
srand (time(NULL));
num1 = rand()%HIGH_NUMBER;
num2 = rand()%HIGH_NUMBER;
num3 = rand()%HIGH_NUMBER;
if ((num1%2==0||num2%2||num3%2==0)&&(num1%2==1||num2%2==1||num3%2==1)&&(num1>50||num2>50||num3>50))
{
return num1,num2,num3;
i--;
printf("%d %d %d",num1,num2,num3);
}
}
while (i);
}

Your function does not set the calling variables as you hoped for. You can't return more than one function value - and it makes no difference that you gave the same names to the variables in main and in the function - they are different variables, and as you wrote it, main just passes copies of those variable values.
Instead I pass pointers to those variables in this example. I also removed the return value of the function, since it now always returns valid values as your spec.
I removed srand within the function. It should be called once only, especially as I call the function 3 times in this example to show different results. If left in the function, all 3 calls would probably give the same result (unless a one-second timer boundary is bridged).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_NUMBER 100
void ValidNumbers(int *num1, int *num2, int *num3); // pointer arguments
int main(void)
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
int tries;
srand ((unsigned)time(NULL)); // call once
for(tries=0; tries<3; tries++) {
ValidNumbers(&num1, &num2, &num3);
printf("%-2d %-2d %-2d\n", num1, num2, num3);
}
return 0;
}
void ValidNumbers(int *num1, int *num2, int *num3)
{
do {
*num1 = rand() % HIGH_NUMBER; // write through pointer of passed var
} while (*num1 <= 50); // number > 50
do {
*num2 = rand() % HIGH_NUMBER;
} while (*num2 % 2 != 0); // even number
do {
*num3 = rand() % HIGH_NUMBER;
} while (*num3 % 2 == 0); // odd number
}
Program output:
79 16 79
95 2 37
73 28 93

Returning multiple values is not allowed in C. So
return num1,num2,num3;
this will not work.
You can use a struct with 3 numbers and return that instead. You can go through this for an example of how do go about it.
Also note that the statement inside if after the return statement will never get executed, and are thus useless..
return num1,num2,num3;
i--; // <-- this will never get executed
printf("%d %d %d",num1,num2,num3); // <-- this will never get executed

There are two ways in C to return multiple parameters
One is mentioned above using 1 struct to hold all the return values inside struct.
Another is using pointer/address to hold the values.
I revised the script to show both ways. I will add a positive comment for HelloWorld, you guys are too harsh, it is an important concepts in c:
#include <stdlib.h>
#include <stdio.h>
#define HIGH_NUMBER 100
typedef struct Random Random;
Random *isValidNumbers(int *num1,int *num2, int *num3);
struct Random{
int a;
int b;
int c;
};
int main(void)
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
/* pr to use as parameter, rr used as a return struct , just for demoo purpuse*/
Random *p;
p = isValidNumbers(&num1,&num2,&num3);
printf("%d %d %d main return random numbers\n",num1,num2,num3);
printf("%d %d %d main return from struct \n",p->a,p->b,p->c);
return 0;
}
Random *isValidNumbers(int *num1,int *num2, int *num3)
{
struct Random *r = malloc(sizeof(Random));
int i=1,ans = 0;
do
{
srand (time(NULL));
*num1 = rand()%HIGH_NUMBER;
*num2 = rand()%HIGH_NUMBER;
*num3 = rand()%HIGH_NUMBER;
r->a = *num1;
r->b = *num2;
r->c = *num3;
if ((*num1%2==0||*num2%2||*num3%2==0)&&(*num1%2==1||*num2%2==1||*num3%2==1)&&(*num1>50||*num2>50||*num3>50))
{
i--;
printf("%d %d %d inside isValidNumber\n",*num1,*num2,*num3);
break;
}
}
while (i);
return r;
}
Results:
cmake28 ..
make
[gliang#www build]$ ./src/random
99 99 44 inside isValidNumber
99 99 44 main return random numbers
99 99 44 main return from struct

Related

How can I use two random numbers generated in a function as matrix coordinates?

I came up with this function to generate two random numbers, r and c, so that I can use them in as coordinates in matrix board[r][c]. Is this even possible?
int coordAleatoria()
{
srand((unsigned int)time(0));
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("%d %d", r, c);
return r;
return c;
}
This is for a chess-like game. The PC is supposed to generate random moves. This function does generate coordinates, I'm just not sure how to make my program treat them as coordinates.
I hope I can get r and c in board[r][c] to be the values generated in coordAleatoria().
You cannot return more than one time. So you can combine the coordinates using structure as Jabberwocky suggested in the comment. If you are still finding it difficult than here is the implementation.
#include<stdio.h>
#include<stdlib.h>//for rand()
#include<time.h>//for time()
struct Pair
{
int row,col;
};
struct Pair coordAleatoria()
{
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("Inside function: row=%d and col=%d\n",r,c);
//Create a pair
struct Pair p;
//Assign values
p.row=r,p.col=c;
//return it
return p;
}
int main()
{
srand((unsigned int)time(0));
//Get the returned value as a Pair
struct Pair p=coordAleatoria();
//Collect the row and column values
int r=p.row;
int c=p.col;
//Now you can use them here
printf("Outside function: row=%d and col=%d\n",r,c);
}
rand()%9 generates 9 different values. With while(r==c), looks like code is looking for 9*(9-1) or 72 different pairs. For a speedier approach, call rand() once.
Code could return a single int and later divine/mod by 9 to recover the row/column.
srand((unsigned int)time(0)); should not be repeated called in coordAleatoria(). Call it once, perhaps in main().
int coordAleatoria(void) {
int rc = rand()%72;
int r = rc/9;
int c = rc%9;
if (r==c) r++;
return (r*9) + c;
}
Rather than calling rand() twice (after properly seeding the random number generator with a call to srand()), you can simply call rand() once and take the first two digits as your coordinates, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int x, y;
} pair_t;
void rand_coords (pair_t *coords)
{
int n = rand();
coords->x = n % 10;
n /= 10;
coords->y = n % 10;
}
int main (void) {
pair_t coords = { .x = 0 };
srand (time (NULL)); /* seed random number generator */
rand_coords (&coords);
printf ("coords.x : %d\ncoords.y : %d\n", coords.x, coords.y);
return 0;
}
(or take the modulo of whatever your actual coordinate range is)
Example Use/Output
$ ./bin/coords_rand
coords.x : 9
coords.y : 8
$ ./bin/coords_rand
coords.x : 1
coords.y : 1
$ ./bin/coords_rand
coords.x : 5
coords.y : 7
$ ./bin/coords_rand
coords.x : 8
coords.y : 0

SUM Recursive function in C

I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs.
I have this and i think it should work but i'm not entirely sure why its not
#include <stdio.h>
int main()
{
int sum (x, max);
int total, y, x, max;
if (x<max){
y=x+1;
total = x+sum(y,max);
return total;
return x;
}
return 0;
}
Thanks for any help with this in advance!
Here is one possible solution:
#include <stdio.h>
int sum_in_range(int a, int b){
if(a != b){
return sum_in_range(a+1,b)+a;
}
else{
return b;
}
}
int main(void) {
// your code goes here
printf("%d",sum_in_range(2,4));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int sum(int s,int max)
{
if(s==max)
{
return s;
}
else
{
return(s+sum(s+1,max));
}
}
int main()
{
int r,s,max;
printf("\n enter s and max");
scanf("%d%d",&s,&max);
r=sum(s,max);
printf("%d",r);
}
I spotted some errors on your code. I'm not a pro yet but here's what I think
I just edit your code. removed, added and rearranged some stuff*/
/*First, let's look at your code*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum(x, max);//I think what you want to do here is declare a function but instead declaring, you define it here because you added semicolon (;)
int total, x, y, max;
if(x < max)
{
y = x + 1;
total = x + sum(y, max); //you don't have a function declaration for "sum"
return total;
return x; //this will never return since you already "return the total before this"
}
return 0;
}
//////////////////////////////////////////////////////////////
/*And I think this is what you want to do*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6; //We declare this here for the "sum" function. This way "sum" function can recognize these variables
int total = x; //be sure to set the total to x.
//you can make a void function for this instead of "int". but either way, it can do the job.
void sum(int y) //no need to pass a "max" because "max" is already recognized by the "sum" function since we declare the variables at the top of "main" function
{
if(x < max)//don't make it x <= max. Because of the argument "total = total + (x + 1)" on this function. If you do, the total will exceed.
{
//You can see here why we set the value of "total" to x.
total = total + (x + 1);//And also, you can see why we didn't make the argument in if() statement like this: if(x <= max).
x++;//increment "x" every loop
//call the function again and pass the total until x == max.
sum(total);
}
}
//pass the x
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
//////////////////////////////////////////////////////////////
/*It looks messy with comments*/
/*Here's the code looks like without a comment.It's pretty short code if you look remove the comments.. LOL..*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6;
int total = x;
void sum(int y)
{
if(x < max)
{
total = total + (x + 1);
x++;
sum(total);
}
}
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}

How do you retrieve a number from a function to use it in another function?

(C code) Each die has its own function, and I want a function that will sum the outcome of each die. But how do I retrieve the values from the first and second functions and put them into the third to sum them? See below
int roll_die1(void)
{
int random_int;
srand((unsigned int)time(NULL));
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);
return random_int;
}
int roll_die2(void)
{
int random_int2;
srand((unsigned int)time(NULL));
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);
return random_int2;
}
int calculate_sum_dice(int die1_value, int die2_value)
{
int sum = die1_value + die2_value;
return sum;
}
Now I can't just call the first two functions into the 3rd function, because it would repeat all the steps in those functions, so how do I do it?
Edit: In my main.c, to get the sum I did
roll1 = roll_die1();
roll2 = roll_die2();
sum = calculate_sum_dice(roll1, roll2);
Just allow calculate_sum_dice() to retrieve both results from roll_die1() and roll_die2() and return the sum. Their is no need to include any function parameters for calculate_sum_dice(). You can also just call srand() once in main(), as it just sets a seed for rand(), so it would be pointless to call it more than once. Have a look at srand(): why call it just once?, as pointed out by #Jonathan Leffler in the comments.
Here is what your code should look like:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int roll_die1(void) {
int random_int;
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);
return random_int;
}
int roll_die2(void) {
int random_int2;
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);
return random_int2;
}
int calculate_sum_dice(void) {
int sum = roll_die1() + roll_die2();
return sum;
}
int main(void) {
srand((unsigned int)time(NULL));
int sum = calculate_sum_dice();
printf("Dice sum = %d\n", sum);
return 0;
}

accessing values in a struct array

I am passing in an array into a function straightflush. I use a counting loop so i can get to all of the elements but for some reason, even tho the counter i increases, i get the value and suit for the first element of the array. Therefore, only my spadesCount increases as it always shows 4 for the value and spade for the suit.
struct card{
int value;
char suit;
};
int straightflush(struct card hand[], int n)
{
int clubsCount = 0;
int diamondsCount = 0;
int heartCount = 0;
int spadesCount =0;
int i;
for(i=0; i<n; i++)
{
if (hand[i].suit == 'c')
{
clubsCount++;
}
else if (hand[i].suit == 'd')
{
diamondsCount++;
}
else if (hand[i].suit == 'h')
{
heartCount++;
}
else{
spadesCount++;
}
}
return 0;
}
here is my main:
int main(){
struct card hand1[] = {{4,'s'}, {9,'s'},{12,'c'},{11,'s'},{8,'s'},
{6,'d'}, {3,'d'},{7,'s'},{10,'s'},{12,'d'}};
printf ("%d\n", straightflush(hand1, 10));
}
I just run your code and the four count variables have correct values. I think it's because you are returning 0 at the end of your straightflush function, the output is always 0.
You can use a debugger or add the following line before the return statement in straightflush() to prove that your counts are actually accurate.
printf("%d %d %d %d\n", clubsCount, diamondsCount, heartCount, spadesCount);
Your return value has nothing to do with the values you read thus the printf statement in your main() function is not printing the count of any thing, it is just printing 0 no matter what.
If you want the counts accessible outside of striaghtflush() you need to either use global variables for those counts (a generally shunned idea) or pass some values in by reference. An example of this would be:
#include <stdio.h>
#include <stdlib.h>
void editValues( int *numDiamonds, int *numClubs, int *numHearts, int *numSpades ){
*numDiamonds = 3;
*numClubs = 5;
*numHearts = 7;
*numSpades = 11;
}
int main(int argc,char**argv)
{
int numD=0, numC=1, numH=2, numS=3;
printf("%d %d %d %d\n", numD, numC, numH, numS);
editValues(&numD, &numC, &numH, &numS);
printf("%d %d %d %d\n", numD, numC, numH, numS);
return 0;
}

Random number generator C

I can't seem to figure out why this is not working. I am trying to get these two void functions to generate randoms numbers when called in the main. I think the problem has to do with srand(time(NULL)); in the void function's. I think that when it gets called in the main and runs in the for loop, srand(time(NULL)); is not updated so it prints out the same number x times. numGen_10 should generate 1-10 and numGen_4 should generate 1-4 based on a variable.
What can I do to get the functions to output different random numbers each time the function is called?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void numGen_10(int xOry, int* xRey);
void numGen_4(int num, int choice, int *choiceRe);
int main()
{
int x;
int num = 5;
for (int i = 0; i < 3; i++)
{
numGen_10(x, &x);
printf("val : %d \n", x);
}
printf("------------------------\n");
for (int i = 0; i < 4; i++)
{
numGen_4(4, x, &x);
printf("val2 : %d \n", x);
}
return 0;
}
void numGen_10(int xOry, int *xRey)
{
srand(time(NULL));
int r = rand() % 10 + 1;
xOry = r;
*xRey = xOry;
return;
}
void numGen_4(int num, int choice, int *choiceRe)
{
srand(time(NULL));
choice = rand() % num + 1;
*choiceRe = choice;
return;
}
The random number generator is completely deterministic; it will always output the same sequence of numbers for any given seed. srand() seeds the random number generator. So by calling srand() with the time immediately before each call to rand(), and since your loops will take less than a second to execute, you'll always get the same random number (or maybe two if the time happens to change in the middle).
Try calling srand() once before entering the loops.
Just for fun , add a delay of 1 second before each srand call when calling srand multiple times :
sleep(1);
/* or delay(1001); or usleep(500000);usleep(500000); based on availability */
srand(time(NULL));
Additional to what others said about solving problem of srand I would like to add a remark about how you use pointers, calling your functions with x and &x is pointless, you can just call either with pointer only or with variable only:
calling with pointer :
void numGen_10(int* xRey); // prototype
void numGen_10(int *xRey) // function's body
{
int r = rand() % 10 + 1;
*xRey = r;
return;
}
numGen_4(4, &x); // use from the main function
calling with variable :
int numGen_10(int xRey); // prototype
int numGen_10(int xRey) //function's body
{
int r = rand() % 10 + 1;
return r;
}
int y = numGen_4(4, x); // use from the main function

Resources