Random Numbers in C

Joined
Oct 25, 2009
Messages
59
Reaction score
0
Points
6
OK, I have been trying for about an hour now to get this to work. I'm trying to generate a random number and display a line of text based on that number. This is what I have so far.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	
	srand(time(NULL));
	int number = rand() % 3;
	
	if (number = 1)
		printf("This is the first line of text.\n");
	
	if (number = 2)
		printf("This is the second line of text.\n");
}

I want this to print either "This is the first line of text." or "This is the second line of text.". When I compile and run it, it prints both. Can someone help me with this?
 
Joined
Dec 13, 2007
Messages
256
Reaction score
10
Points
18
Location
United States of America
Your Mac's Specs
2.1GHz MacBook with 4GB RAM, Mac OS X 10.6, iLife and iWork ‘09
I assume you figured it out, but just in case you didn't, the problem is that you're using the assignment operator (=) in your comparisons instead of the correct == operator. Also, considering that you want to print either one line of text or the other, you might want to consider using an if/else construction.
 

Raz0rEdge

Well-known member
Staff member
Moderator
Joined
Jul 17, 2009
Messages
15,765
Reaction score
2,105
Points
113
Location
MA
Your Mac's Specs
2022 Mac Studio M1 Max, 2023 M2 MBA
Also, you aren't accounting for the very real possibility that number = 0. If you only want to check for 1 and 2, then you need "(rand() % 3) + 1)" to cover that..

Regards
 
Joined
Dec 13, 2007
Messages
256
Reaction score
10
Points
18
Location
United States of America
Your Mac's Specs
2.1GHz MacBook with 4GB RAM, Mac OS X 10.6, iLife and iWork ‘09
Also, you aren't accounting for the very real possibility that number = 0. If you only want to check for 1 and 2, then you need "(rand() % 3) + 1)" to cover that..

Regards
Or more simply, if only two options are wanted, int number = rand() % 2; followed by a check for 0 or 1 would be best.
 

Shop Amazon


Shop for your Apple, Mac, iPhone and other computer products on Amazon.
We are a participant in the Amazon Services LLC Associates Program, an affiliate program designed to provide a means for us to earn fees by linking to Amazon and affiliated sites.
Top