Initialize variable
I have a code like this from cprogramming.com, I don't understand why "guess" has to be -1. How about initialize it 0?
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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int num = rand() % 100;
int guess = -1;
int trycount = 0;
while (guess != num && trycount < 8)
{
cout << "Enter your guess: ";
cin >> guess;
if (guess < num)
{
cout << "Wrong! You entered the smaller number! Try again!\n";
}
if (guess > num)
{
cout << "Wrong! You enter a higher number! Try again!\n";
}
trycount++;
}
if (guess == num)
{
cout << "You're right! Woo hoo! Hello smart guy! :)\n";
}
else
{
cout << "You fool! The number is " << num << endl;
}
}
|
> How about initialize it 0?
num (
rand() % 100) may be equal to zero.
Somewhat more compact:
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>
int main()
{
std::srand( std::time(nullptr) );
const int num = std::rand() % 100 ;
int guess ;
for( int trycount = 0 ;
std::cout << "Enter your guess: " && std::cin >> guess && guess != num && trycount < 8 ;
++trycount )
{
if (guess < num) std::cout << "Wrong! You entered the smaller number! Try again!\n";
else std::cout << "Wrong! You enter a higher number! Try again!\n";
}
if (guess == num) std::cout << "You're right! Woo hoo! Hello smart guy! :)\n";
else std::cout << "You fool! The number is " << num << '\n' ;
}
|
Why does num(rand % 100 ) can be 0? Sorry, I just don't get it clearly!
n%100 == 0 if n is an integral multiple of 100
0%100 == 0, 100%100 == 0, 200%100 == 0 etc.
God! How about 2?
See:
http://www.cprogramming.com/tutorial/modulus.html
Try this out:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
int main()
{
for( int n : { 0, 2, 100, 700, 567, 1789 } )
{
std::cout << n << " % 100 == " << n % 100 << '\n'
<< -n << " % 100 == " << -n % 100 << '\n'
<< n << " % -100 == " << n % -100 << '\n'
<< -n << " % -100 == " << -n % -100 << "\n\n" ;
}
}
|
Thank you!
Topic archived. No new replies allowed.