Allright,,
To begin with, I'm just a total beginner.
I've started programming a week ago, and I've stumbled upon the "Guess My Number" program. Here is the code I used for the program:
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
|
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand(static_cast<unsigned int>(time(0))); //seed the random number generator
int secretNumber = rand() % 100 + 1; // create random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
|
This works all fine,, But I wanted to make it a bit more interesting,, and let the computer guess My number. Here is what I did:
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
|
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand(static_cast<unsigned int>(time(0)));
int tries = 0;
int iNum;
int iCompNum = rand() % 100 + 1;
cout << "\tWelcome to Guess My Number\n\n";
cout << "in this version, the computer tries to guess YOUR number\n\n\n";
cout << "Enter a number: ";
cin >> iNum;
do
{
cout << "\nComputer's guess: ";
cout << iCompNum;
++tries;
if (iNum > iCompNum)
{
cout << "\nYou're too low..!\n\n";
iCompNum;
}
else if (iNum < iCompNum)
{
cout << "\nToo high..!\n\n";
iCompNum;
}
else if (iNum == iCompNum)
{
cout << "\nYou got my number, You're the man!\n\nYou guessed the number in just " << tries << " tries!\n\n";
}
iCompNum = rand() % 100 + 1;
} while (iNum != iCompNum);
return 0;
}
|
Again,, I'm just a total beginner and don't even know everything I'm writing down. But I thought this would come close to what I wanted to write.
Here are the problems I get with this code:
1) It only goes for a several amount of tries, which is diffrent everytime. And that sounds like it's good, I mean, if it guessed the number, it should stop. But that's where the problem comes up: It stops, but not on the right number. Just a random one.
2) I know there's nothing of this in the code, but I wanted it to listen to the "Go higher" and "Go lower" lines. How do I do that?
-- Any help is Great help,, Thanks!! --
P.S. I know there's another post about this, But in that post the person writes in a whole diffrent way. And I would like (not selfish ment) to write it down this way. Thanks!