C++ functions and random number - c++

When I write this code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
}
}
Every time I run it I get something else printed(Wolf, Pig or Bear), like I wanted.
But when I add this function in my code like this:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
void func(){
if(random==1 || random ==2 || random == 3){
cout << "Wolff" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bearr" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pigg" << endl;
}
}
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
func();
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
func();
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
func();
}
}
I want every time I run it to get printed something else like Bear Bearr, Wolf Wolff or Pig Pigg.But with this function whenever I run it I get the same result.What is the problem?
Please help me, I'm new in C++.

The global initializers are executed before main is called. So you never reseed your PRNG, and thus always draw the same "random" numbers.
That said, I don't believe that either of your code pieces produce different output with each run, since they have the same initialization order problem.

EDIT: Changing to match your stated goal of "bear", "bearr", "pig", "pigg".
int random = std::rand() % 9 + 1;
declares a global variable called "random" which is assigned a value during startup, before main(). The value will be the (default return value of rand() modulo'd by 9) plus one. It does not automatically change.
What you appear to be looking for is
int random()
{
return (std::rand() % 9) + 1;
}
which defines a function that calls rand, modulos the value by 9 and then returns one. EDIT: To see the same value inside the "func()" function, pass it by value or reference as a function parameter:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
int random() {
return (std::rand() % 9) + 1;
}
void func(int randNo){
switch (randNo) {
case 1: case 2: case 3:
cout << "Wolff" << endl;
break;
case 4: case 5: case 6:
cout << "Bearr" << endl;
break;
case 7: case 8: case 9:
cout << "Pigg" << endl;
break;
}
}
int main()
{
std::srand(std::time(0));
int randNo = random();
switch (randNo) {
case 1: case 2: case 3:
cout << "Wolf" << endl;
func(randNo);
break;
case 4: case 5: case 6:
cout << "Bear" << endl;
func(randNo);
break;
case 7: case 8: case 9:
cout << "Pig" << endl;
func(randNo);
break;
}
cout << "And now for something completely different." << endl;
for (size_t i = 0; i < 10; ++i) {
cout << i << ": ";
func(random());
}
}

Related

If else statement not running C++

I am trying to make a simple guess the number game and when the answer is bigger than the number the if else statement does not trigger.
For example if the number is 20 and I choose something above 30 say 41 it will just end the code.
#include <iostream>
#include <string>
#include <cmath>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <fstream>
#include <random>
#include <time.h>
#include "functions.h"
using namespace std;
void game() {
int number;
int answer;
cout << "Welcome to the guess the number game!" << endl;
cout << "The computer will generate a random number from 1 to 100 and you will try to guess it."<< endl;
cont();
ran(number,100,1);
START:
cout << number;
system("clear");
cout << "Type your answer here: ";
if (!(cin >> answer)) {
cin.clear();
cin.ignore(10000,'\n');
cout << "THAT IS NOT AN OPTION!" << endl;
sleepcp(250);
system("clear");
goto START;
}
int warmer1;
int warmer2;
warmer1 = number + 11;
warmer2 = number - 11;
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
cout << "Less." << endl;
sleepcp(250);
system("clear");
goto START;
} else if (answer < number) {
cout << "More."<< endl;
sleepcp(250);
system("clear");
goto START;
}
}
int main() {
game();
return 0;
}
Can anybody help with this thanks!!!
Consider this if statement when number is equal to 20 and answer is equal to 41.
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
In this case the if statement gets the control because answer is greater than warmer2. But answer is not equal to number (the first inner if statement) and answer is not less than warmer1.
In this case nothing occurs and the control is passed to the end of the program.
That is if this if statement
if (answer > warmer2) {
gets the control then the following if statements like for example this
} else if (answer > number) {
will be skipped.
In other words, what you do is what you get.
You could resolve your problem if instead of goto statements you used for example a while or do-while loop.
If you were to step through your code with a debugger (or at least print out some diagnostic messages describing your game's decisions), you would see exactly why the program is terminating.
Assuming number is 20 and answer is 41, then warmer1 is 31 and warmer2 is 9, thus:
void game() {
...
START:
...
if (answer > warmer2) { // 41 > 9 is TRUE
if (answer == number) { // 41 == 20 is FALSE
...
} else if (answer < warmer1) { // 41 < 31 is FALSE
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
} else if (answer > number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
} else if (answer < number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
}
Since the game() function does not reach a goto START; statement, the loop ends and game() exits, and thus main() exits, terminating the program.
There is almost never a good reason to use goto in modern C++ coding. Use a while or do..while loop instead, eg:
#include <iostream>
#include <limits>
#include "functions.h"
using namespace std;
void game() {
int number, answer, warmer1, warmer2;
cout << "Welcome to the guess the number game!" << endl;
cout << "The computer will generate a random number from 1 to 100 and you will try to guess it." << endl;
cont();
ran(number, 100, 1);
warmer1 = number + 11;
warmer2 = number - 11;
do {
system("clear");
cout << "Type your answer here: ";
if (!(cin >> answer)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "THAT IS NOT AN OPTION!" << endl;
}
else if (answer == number) {
cout << "You got it!";
break;
}
else {
if (answer <= warmer1 && answer >= warmer2) {
cout << "You are close." << endl;
}
if (answer > number) {
cout << "Less." << endl;
}
else {
cout << "More."<< endl;
}
}
sleepcp(250);
}
while (true);
}
int main() {
game();
return 0;
}

expected unqualified id before return 0

I'm new to C++. I have errors. But, i dont know how to fix it. Could anyone please help me? Thank you.
P - Print numbers
A - Add a number
M - Display mean of the numbers
S - Display the smallest number
L - Display the largest number
Q - Quit
Errors : expected unqualified id before return 0
error : expected ';' before {}
#include <iostream>
#include <vector>
using namespace std;
int main(){
char input {};
vector <double> numbers {};
int number{};
int sum{};
int min_number{};
int max_number{};
bool condition {true};
cout << "Enter a command" << endl;
cin >> input;
if(numbers.size() > 0){
while(condition){
if (input == 'P' || input == 'p'){
for(auto x: numbers)
cout << x << endl;
}
else if(input == 'A' || input == 'a'){
cout << "Enter a number";
cin >> number;
numbers.push_back(number);
}
else if(input == 'M' || input == 'm'){
for(auto x : numbers)
sum += x;
cout << sum / numbers.size() << endl;
}
else if(input =='S' || input == 's'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) < min_number)
min_number =numbers.at(i);
}
else if(input =='L' || input == 'l'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) > max_number)
max_number =numbers.at(i);
}
else if(input =='Q' || input == 'q'){
condition {false};
}
}
cout << "[] - list is empty, unable to calculate" << endl;
}
return 0;
}
In your section dealing with Q/q, the statement:
condition {false};
is not a valid form of assignment, you should instead use:
condition = false;
The braces are fine for initialisation, but that's not what you're trying to do on that line.
As an aside, this line:
if(numbers.size() > 0){
seems a little strange. Since you initialise the list to empty, the main loop will never start (because it's inside the if block) even though you have already asked the user for input.
That's a runtime error rather than a syntax error but you'll still need to fix it at some point.
I suspect that particular should should be done only as part of the calculation of the mean, so as to avoid dividing by zero.
I have written this for you. Since, you're a learner, I think that you should be practicing better things like STL functions and not using using namespace std; at top.
You may find some things new, but don't be frightened, just search them on some website like cppreference and see what that entity do and how to effectively use it.
There were many logical errors. #paxdiablo has mentioned them in his answer. I have removed every of them and this code works.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>
int main() {
std::vector<double> numbers;
while (true) {
char input;
std::cout << "Enter a command: ";
std::cin >> input;
switch (std::toupper(input)) {
case 'P':
if (numbers.empty())
std::cerr << "The list is empty!" << std::endl;
else {
for (auto &&i : numbers)
std::cout << i << ' ';
std::cout << std::endl;
}
break;
case 'A': {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
numbers.push_back(number);
break;
}
case 'M':
if (numbers.empty())
std::cerr << "The list is empty! Cannot perform the operation!!";
else {
int sum = 0;
for (auto &&i : numbers)
sum += i;
std::cout << "Mean: " << (sum / numbers.size()) << std::endl;
}
break;
case 'S':
std::cout << "Smallest Number: " << *std::min_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'L':
std::cout << "Largest Number: " << *std::max_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'Q':
return 0;
default:
std::cerr << "Unrecognised Command!!" << std::endl;
}
}
return 0;
}

Switches in C++

I am new to C++ and programming in general and was trying to figure out a way to create a switch in C++ to trigger when a number entered is divisible by 3, by 5, and by both 3 and 5. Here is what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number;
cout << "Please input a number and then press the enter key" << endl;
cin >> number;
switch (number){
case "/3":
cout << "Fizz" << endl;
break;
case "/5":
cout << "Buzz" << endl;
break;
case "/3" "/5":
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
Any help with this would be greatly appreciated! :)
In C++ the switch labels must be compile-time evaluable constant expressions that are integral types.
"/3", for example, is a string literal and so does not fit that requirement.
In this case, use number % 3 == 0 to test for divisibility by 3, and so on and use an if, else block:
if (number % 15 == 0){
/*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
} else if (number % 3 == 0){
/*Fizz*/
} else if (number % 5 == 0){
/*Buzz*/
}
You can use if else.
int remainder1 = 0, remainder2 = 0;
remainder1 = number % 3;
remainder2 = number % 5;
if(remainder1 == 0 && remainder2 ==0) // both
cout<<"FizzBuzz"<<'\n';
else if(remainder1 == 0) // number can be divided by 3
cout<<"Fizz"<<'\n';
else if(remainder2 == 0) // number can be divided by 5
cout<<"Buzz\n";
else // neither
cout<<"......"<<'\n';
BTW, you do have to read the basic book about C++.
here, you can know more about switch
If you really want to do with switch, here is a method, but is not nice. The easiest way is how Bathsheba said.
#include <iostream>
#include <cmath>
using namespace std;
enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; // "strong enum"
// enum class divided { DivideBy3 , DivideBy5 , DivideBy3and5 }; //also good but can be unsafe
divided getCase(int number)
{
divided div;
if(number%3 == 0)
div = divided::DivideBy3;
if(number%5 == 0)
div = divided::DivideBy5;
if(number%3 ==0 && number%5 == 0)
div = divided::DivideBy3and5;
return div;
}
int main()
{
int numberIn;
cout << "Please input a number and then press the enter key" << endl;
cin >> numberIn;
divided number = getCase(numberIn);
switch (number)
{
case divided::DivideBy3:
cout << "Fizz" << endl;
break;
case divided::DivideBy5:
cout << "Buzz" << endl;
break;
case divided::DivideBy3and5:
cout << "FizzBuzz" << endl;
break;
default:
cout << "Please select another number." << endl;
}
}
look at this for enum vs class enum. Keep going.

Decimal to binary/hex using arrays

I'm having trouble with the hexadecimal part of my c++ program. When I use the switch for hexadecimal nothing returns. also for some reason my binary conversion has a leading 0 I cant seem to get rid of.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
void binary(int, int);
void hex(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
int numb, base;
cout << "Enter a decimel number : ";
cin >> numb;
cout << "Enter a base you want number switched to: ";
cin >> base;
switch (base){
case 2: binary(numb, base); break;
case 8: break;
case 16: hex(numb, base); break;
default: break;
}
}
void binary(int numb, int base)
{
int bin[32] = { 0 };
int i = 0;
do
{
bin[i] = numb%base;
numb = numb / base;
i++;
} while (numb != 0);
cout << "\n";
while (i >= 0){
cout << bin[i];
i--;
}
cout << endl << endl;
}
void hex(int numb, int base){
int i;
int hex[10] = { 0 };
for (i=0; i > 10; i++){
hex[i] = numb%base;
numb = numb / base;
for (i; i > 0; i--)
{
if (hex[i] >= 10)
{
switch (hex[i]){
case 10: cout << "A"; break;
case 11: cout << "B"; break;
case 12: cout << "C"; break;
case 13: cout << "D"; break;
case 14: cout << "E"; break;
case 15: cout << "F"; break;
default: break;
}
}
cout << hex[i];
}
}
cout << endl;
}
binary
The problem is after the first loop, i is one greater than the last index. Just for example, say you enter 1: the do...while loop is entered, the digit 1 is put in array index 0, then i is incremented to 1.
Then, in the second loop, both indexes 1 and 0 are printed. You can solve this by decrementing i before entering this loop:
i--;
while (i >= 0){...}
You should be doing something like that anyway, because if you ended up using all 32 digits, you would try to access bin[32] and the program may crash or output gibberish.
hex
The first loop's condition is infinite:
for (i = 0; i >= 0; i++){...}
It should be the same as your condition in binary:
for (i = 0; numb != 0; i++){...}
But you are not done yet because I've noticed you also have a bug in your printing:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
cout << hex[i];
If hex[i] is greater than or equal to 10, it gets printed twice, once as a hex letter and once as a decimal number. To solve this you could, for example, use continue instead of break in your switch (to skip the second print), or use else:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
else
{
cout << hex[i];
}
You also need to make the same correction as in binary:
// decrementing i before entering the loop
// vvv
for (i--; i >= 0; i--){...}
Your revision is not correct, hex should not have a nested loop. It was fine before, just with the corrections I've pointed out.

Redefiniton of an int error

I'm teaching my self C++ on the side and i realize this question may seem remedial to some. In the game I'm making as part of the learning process I want the user to be able to pick a difficulty and when they pick one or the other the random number value range changes. The compiler I'm using is x-Code by the way. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
int secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
int secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
int secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
The 2 errors occur in case 2 and 3 where i try to redefine the value of secretNumber.
The case blocks do not open different scopes, but are rather part of the same block. Your code (considering only scopes) looks somehow similar to:
int secretNumber;
{
int secretNumber = rand() % 10 + 1;
...
int secretNumber = rand() % 50 + 1;
...
int secretNumber = rand() % 100 + 1;
}
Three different variables with the same name are being declared in the same scope, which is not allowed in the language. Note that all three declarations inside the switch would also hide the variable declared in the outer scope, which is probably not what you want anyway.
It looks like you have some background in some other languages - perhaps a functional language and perhaps some JavaScript.
One of the key features of C++ is scoping. Variables (named value holders) have a lifetime of the scope they are within, and variables are only visible within the scope they are defined. (Not to be confused with objects, which through pointers and allocation can be teased off the stack and into heap memory, only to be lost when the variables with their address go out of scope if they are not properly deallocated).
{
int i = 1;
}
std::cout << "i is " << i << std::endl; // compiler error, i does not exist here.
void foo() {
int i = 1;
}
void bar() {
foo();
std::cout << i << std::endl; // compiler error, i does not exist here.
}
Also, unless decorated as "const", C++ variables are mutable - they can be changed.
int i = 1;
i = 2;
std::cout << i << std::endl; // writes 2, not 1.
So: your code is not 'redefining' secretNumber, it is shadowing the previous definition, hiding it for the duration of the current scope. Thus when you assign a value to the inner version, the "secretNumber" visible to code outside the scope is untouched.
#include <iostream>
int main()
{
int foo = 1; // outer foo
std::cout << "Originally, foo = " << foo << std::endl;
{
int foo = 2; // inner foo
std::cout << "Inside the inner scope, foo = " << foo << std::endl;
}
// inner foo doesn't exist here, so it references outer foo.
std::cout << "But the original foo still exists, " << foo << std::endl;
}
What you actually want to do is simply assign a new value to the original secretNumber variable you declared in the outer scope, since that is the only variable named "secretNumber" available to code in that scope.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
This is one reason why many C++ programmers choose to use prefix and suffix notations to distinguish certain types of variables:
#include <iostream>
class Foo {
public:
int m_i; // member variable, m_xxx
Foo(int); // constructor taking an int.
};
static int s_i;
Foo::Foo(int i_) // arguments use _ suffix
{
int i = i_; // local value of i
i *= 3;
m_i = i; // we're assigning it the local value, not the argument.
}
int main()
{
int i = 1;
Foo foo(2);
s_i = 3;
std::cout << "i = "<<i<<", foo.m_i = "<<foo.m_i<<", s_i = "<<s_i<< std::endl;
}
Live Demo: http://ideone.com/dSTwPT
You are getting the compile time error because you are redeclaring the same variable within the same scope (case statement block level scope). You need to delete int before secretNumber in all the case statements. Doing otherwise, the secretNumber variable declared at the while loop block level will stay undefined.