Would this work?

Would this code(if compiled in gcc) work?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
	srand((unsigned)time(0));
	int random_integer;
	for(int index=0; index<20; index++){
		random_integer = (rand()%6)+1; 
	}
	int move;
	cout << "Would you like to go left, right, up, or down?(l,r,u,d)";
	cin >> move;
	if (move == 'l'){
		if (random_integer > 4){
			cout << "You got a apple";
		}
		else{
			cout << "You found nothing";
		}
	}
	if (move == 'r'){
		if (random_integer > 4){
			cout << "You got a apple";
		}
		else{
			cout << "You found nothing";
		}
	}
	if (move == 'u'){
		if (random_integer > 4){
			cout << "You got a apple";
		}
		else{
			cout << "You found nothing";
		}
	}
	if (move == 'd'){
		if (random_integer > 4){
			cout << "You got a apple";
		}
		else{
			cout << "You found nothing";
		}
	}
	return 0;
}


Im a self taught programmer so this code isnt made well. Im compiling it on ubuntu with gcc with this command g++ game.cpp -o apples. I call it apples because your to press l,r,u,d and if random_interger > 4 then you get a apple. When I run it it shows a line i put in l,r,u, or d and then it exits. Help?
Why are you discarding so many rand() values and why all the duplicate code? This would be enough:
1
2
3
4
5
if (move == 'l' || move == 'r' || move == 'u' || move == 'd')
{
   if (random_integer > 4)cout << "You got a apple";
   else cout << "You found nothing";			
}


Also, you need to read a char, not an int.
1. Im a self taught coding noob. But hey learning from mistakes arent bad.
Maybe I should be clearer. When I compile and run this on ubuntu with gcc it makes the compiled file. I then run it in terminal and then It shows the first line "Where would you like to move?(l, r, u, d)" I input one of those 4 letters and then press enter and it ends. Can someone tell me what im doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
	srand((unsigned)time(0));
	int random_integer;
	for(int index=0; index<20; index++){
		random_integer = (rand()%6)+1; 
	}
	char move;
	cout << "Would you like to go left, right, up, or down?(l,r,u,d)";
	cin >> move;
	if (move == 'l' || move == 'r' || move == 'u' || move == 'd')
	{
   		if (random_integer > 4)cout << "You got a apple";
   		else cout << "You found nothing";			
	}
	return 0;
}
Last edited on
That's what you told it to do.

Line 14 you said to output that text
Line 15 you said to read the user's input
Line 16 you said to do lines 18 and 19 only if the input was l, r, u, or d.
Line 21 says to return 0 from main(), which returning from main() causes the program to end.
woops ill fix that right up soon
Topic archived. No new replies allowed.