For a lab assignment, we are to create an application that generates questions and answers them randomly to determine the kind of animal.
So we have... Is it a vertebrate, then if it isn't we say it's an insect, then if it's not we ask if its it's warm blooded... if not we say it's a reptile if so then we ask if it can fly... if not we say its a mammal, if so then we say its a bird.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
void main()
{
// Declarations
int rn;
// Initialization
srand ( time(NULL) );
// Process
cout << "Is the animal a vertibrate?\n\n";
rn = rand() % 2;
if (rn == 0)
cout << "No: The animal is an insect!\n\n";
elseif (rn ==1) // The program has decided that it is not an insect and is going to execute the block to code to determine the next variable.
cout << "Yes: Not an insect then. Is the animal warm blooded?\n\n";
rn = rand() %2;
if (rn == 0)
cout << "No: This animal is a reptile!\n\n";
elseif (rn == 1)
cout << "Yes: Not a repitle then. Can the animal fly?\n\n";
rn = rand() %2;}
if (rn == 0)
cout << "No: It's a mammal!\n";
elseif (rn == 1)
cout << "Yes: It's a bird! It's a plane! It's SUPERMAN!!!!.... no just a bird" << endl;
system("pause");
}
Instead of it stopping after vertebrate being no and it declaring it an insect... it just cycles through all the questions... which I want it to stop. I know that I can put curly braces to create code blocks to execute this block of code after that... so I can get it to stop after insect and then ask the next question, but then I don't know how to get a third layer of code blocks to do the third question only if the 2nd question is true.
Can someone help me on where to put my code blocks of if I'm missing something all together?
This is basic C++ stuff so I shouldn't use advanced concepts to complete this task... only variables and nested else-if statements.
cout << "Is the animal a vertibrate?\n\n";
rn = rand() % 2;
if (rn == 0)
{
cout << "No: The animal is an insect!\n\n";
}
elseif (rn ==1) // The program has decided that it is not an insect and is going to execute the block to code to determine the next variable.
{
cout << "Yes: Not an insect then. Is the animal warm blooded?\n\n";
}
rn = rand() %2;
if (rn == 0)
{
cout << "No: This animal is a reptile!\n\n";
}
elseif (rn == 1)
{
cout << "Yes: Not a repitle then. Can the animal fly?\n\n";
}
rn = rand() %2;
if (rn == 0)
{
cout << "No: It's a mammal!\n";
}
elseif (rn == 1)
{
cout << "Yes: It's a bird! It's a plane! It's SUPERMAN!!!!.... no just a bird" << endl;
}
It's realy helpful to always put braces around your if statements when you're just learning (I still do it after several years of programming, because it's more consistent) even when you only want them to effect the one line of code. It may take up more space, but it makes it dead clear how the program flow will occur.
You need to put in braces around your code, and carefuly look through which statements will be run when.