I'm stuck on this program it has you generate a random number from 0 to 9 and then you have to output how close they where to the number. I can't get it to show that "Your guess was within 2 of the number" and then you have to show that "your guess is greater than 2 of the number". Any help would be great thanks here my code that i ahve so far.
#include<iostream>
using namespace std;
int main()
{
int num;
cout << "Try and choose a number from 0 to 9 by enterng it now " << endl;
cin >> num;
const int DIVISOR = 10;
const int NUM = 1;
int x;
int result;
srand((unsigned)time(NULL));
for(x = 0; x < NUM; ++x)
{
result = rand() % DIVISOR;
cout << result << " " << endl;
if(result == num)
cout << "You guessed correct" << endl;
else
if (result > num || result < num)
cout << "you were off by 2 " << endl;
else
cout << "You were off by more than 2" << endl;
}
system("pause");
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int num;
cout << "Try and choose a number from 0 to 9 by entering it now " << endl;
cin >> num;
//This bit makes sure the user chooses the correct number.
while(num > 9 || num < 0)
{
cout << "Please choose a number between 0 and 9." << endl;
cin >> num;
}
//
constint DIVISOR = 10;
constint NUM = 1;
int x;
int result;
srand((unsigned)time(NULL));
for(x = 0; x < NUM; ++x)
{
result = rand() % DIVISOR;
cout << result << " " << endl;
if(result == num)
cout << "You guessed correct" << endl;
//
elseif ((num >= result-2) && (num <= result+2))
cout << "You were within 2 " << endl;
//
else
cout << "You were off by more than 2" << endl;
}
// It is bad practice to use system('pause')
//Instead use a loop that ends when the user types 'x'
while(TRUE)
{
char exit;
cin >> exit;
if (exit = 'x')
break;
}
//
return 0;
}
if(result == num)
cout << "You guessed correct" << endl;
//
elseif ((num >= result-2) && (num <= result+2))
cout << "You were within 2 " << endl;
//
else
cout << "You were off by more than 2" << endl;
}
Use what I recommended, it is much easier
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <cmath>
if(result == num)
{
cout << "You guessed correct!\n";
}
elseif( abs(result - num) <= 2)
{
cout << "You were within 2.\n";
}
else
{
cout << "You were not within 2.\n";
}
Instead of system("pause");
Try this.
1 2 3 4
std::cout << "Press Enter to exit...";
std::cin.clear(); // brilliant!
std::cin.sync(); // brilliant!
std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' ); // lets the user type anything up-to and including the Enter key
btw: This code was taken from a post made by Duoas in the Console Closing Down Thread