Reputation:
The question reads:
We would like to be able to classify new animals they are discovered in the wild. We will use the
rand()
function to generate random integers (0 or 1) to represent the No or Yes answers respectively to a series of questions. We can then use the answers to classify animals as either:
- Insects
- Reptiles
- Birds
- Mammals
In each case, the questions continue until an identification is made. For each question asked, a random value is needed for the answer. To identify each animal, use a nested
if
-else
structure.
Here are a few sample program runs with their outputs. Each example is a distinct program run.
Random Animal Generator Is the animal a vertibrate? Yes – Not Insect Is the animal warm-blooded? Yes – Not Reptile Can the animal fly? Yes – The animal is a Bird!
Random Animal Generator Is the animal a vertibrate? No – The animal is an Insect!
Random Animal Generator Is the animal a vertibrate? Yes – Not Insect Is the animal warm-blooded? No – The animal is a Reptile!
I’m so confused. How do I generate all the else if
statements to work and answer in order? How do I make them answer by yes or no, then make them answer again yes or no, etc.? Also how do I make them come out randomly with the rand()
function?
Code:
#include <iostream>
using namespace std;
main () {
char Answer;
cout<<" Random Animal Generator\n";
cout << "Is the animal a vertibrate?(1=Yes/0=No)? ";
cin >> Answer;
if(Answer == '1')
cout << "Not Insect \n";
else (Answer== '0')
cout<<"The animal is an Insect!\n";
cout<<endl;
system("pause");
}
Upvotes: 0
Views: 1696
Reputation: 182829
Here's a start:
#include <iostream>
using namespace std;
int getRandomAnswer()
{ // code here to return a 1 or 0 randomly
}
main () {
cout<<" Random Animal Generator\n";
cout << "Is the animal a vertebrate?";
if(getRandomAnswer() == 1)
{
cout << "Yes - Not Insect \n";
cout << "Is the animal warm blooded?"
if (getRandomAnswer() == 1)
{
// Code for "warm blooded" case goes here
}
else
{
// Code for "not warm blooded" case goes here
}
}
else
{
cout<<"No. The animal is an Insect!\n";
}
cout<<endl;
}
Also, do not use system("pause");
under any circumstances. If you want to wait for a keypress, then do that. But you have no way to know whether there is a command called pause
on other people's machines or, if so, what it does. On my machine, for example, there's a command called pause
that pauses the coolant pump on my home reactor. Imagine the potential harm if I had tested your code on my machine!
Upvotes: 2
Reputation: 61388
The C library has a function rand()
that returns a random number from 0 to RAND_MAX. Now, you want a random number that's a zero or a one. What's a good function that takes a random number and returns a 0/1 with equal probability (or very close to equal)?
Think of properties of natural numbers. You need a property that about half the numbers has and the other half has not.
Upvotes: 0