using rand function in while loop using switch statement

closed account (L092y60M)
Basically I'm supposed to use a while loop to generate a random number and use a switch statement to output the appropriate information.I feel like I'm missing a few things that are very simple.

I'm just very lost.

Thank you.

The errors are:
warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
warning C4700: uninitialized local variable 'randomNumber' used

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main(){
	int i = 0;
	unsigned int randomNumber;

	while(i != randomNumber){
		srand (time(NULL));
		randomNumber = rand() % 100 + 1;

		switch(randomNumber){
		case 100:
			cout << "Wonderful you get the maximum number!" << endl;
			break;
		case 88:
			cout << "Good your number means lucky!" << endl;
			break;
		case 13:
			cout << "I am sorry to tell you got a bad number!" << endl;
			break;
		default:
			cout << "Your number means nothing, please try again" << endl;
			break;
		}
		i++;
	}

	system("pause");
	return 0;
}
Last edited on
Those are warnings so the program should still run.

Two things that I see:

1. Move the srand() statement outside of the while loop.
2. Don't you need a terminating condition in the while loop? If i != randomNumber before i == 100 it will loop forever.
Maybe change your line 12, since you're using a variable (randomNumber) you haven't initialised. uninitialised == bad, you're not even guaranteed your while loop will ever be entered.

if you want to avoid the C4244 warning, explicitly cast the return value of time() to an unsigned int.

Reiterating norm's comments:

srand() should be called just once before entering the loop, to seed your random number generator.

Perhaps initialise by calling rand() once before the loop or in your while condition.

Also find a sane exit strategy.
Topic archived. No new replies allowed.