C++ beginner here. I'm trying to replicate this output and I'm almost there but I'm having trouble with the last part (the quiz percentage).
Example output:
Welcome to our math quiz program! Please enter the answers to the
following questions:
5! = 5
(2^(2^(2^2))) = 65536
3 * (4 + 8) / ((4 * 2) / (5 – 1)) = 18
3 + 2 + 1 + 2 + 3 = 11
Number of correct answers: 3
Number of incorrect answers: 1
Quiz percentage: 75%
Here is my code so far:
int problem4() {
int numCorrect = 0;
int numIncorrect = 0;
int possibleCorrect = 4;
int correctAnswerOne = 120;
int correctAnswerTwo = 65536;
int correctAnswerThree = 18;
int correctAnswerFour = 11;
int guessOne;
int guessTwo;
int guessThree;
int guessFour;
cout << "*** Start of problem 4 ***" << endl;
cout << "Welcome to our math quiz program!" << endl;
cout << "Please enter the answers to the following questions: " << endl;
cout << "5! = ";
cin >> guessOne;
cout << "(2^(2^(2^2))) = ";
cin >> guessTwo;
cout << "3 * (4 + 8) / ((4 * 2) / (5 - 1)) = ";
cin >> guessThree;
cout << "3 + 2 + 1 + 2 + 3 = ";
cin >> guessFour;
switch (guessOne) {
case 120:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessTwo) {
case 65536:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessThree) {
case 18:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessFour) {
case 11:
numCorrect++;
break;
default:
numIncorrect++;
}
cout << "Number of correct answers: " << numCorrect << endl;
cout << "Number of incorrect answers: " << numIncorrect << endl;
cout << "Quiz percentage: " << (numCorrect / possibleCorrect) * 100 << "%" << endl;
cout << endl;
return 0;
}
It seems like when I answer all the questions correctly I get 100% as I should, however, when I score anything but that (only 1, 2, or 3 correct), I end up getting a 0% as a result. I thought I was doing the percentage calculation correctly but the output is suggesting otherwise. Can anybody point me in the right direction? Thanks.
EDIT: Added breaks to switches (however, not root of problem).
Break statements are missing from your switch(s).
Plus you need to type cast the result to float as all the variables are integers. i suggest you use:
float perc;
perc = (numCorrect/possibleCorrect)*100;
You need a break if you switch, and multiply by 100.0 first to implicitly promote the first expression to a double and then divide:
int problem4() {
int numCorrect = 0;
int numIncorrect = 0;
int possibleCorrect = 4;
int correctAnswerOne = 120;
int correctAnswerTwo = 65536;
int correctAnswerThree = 18;
int correctAnswerFour = 11;
int guessOne;
int guessTwo;
int guessThree;
int guessFour;
cout << "*** Start of problem 4 ***" << endl;
cout << "Welcome to our math quiz program!" << endl;
cout << "Please enter the answers to the following questions: " << endl;
cout << "5! = ";
cin >> guessOne;
cout << "(2^(2^(2^2))) = ";
cin >> guessTwo;
cout << "3 * (4 + 8) / ((4 * 2) / (5 - 1)) = ";
cin >> guessThree;
cout << "3 + 2 + 1 + 2 + 3 = ";
cin >> guessFour;
switch (guessOne) {
case 120:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessTwo) {
case 65536:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessThree) {
case 18:
numCorrect++;
break;
default:
numIncorrect++;
}
switch (guessFour) {
case 11:
numCorrect++;
break;
default:
numIncorrect++;
}
cout << "Number of correct answers: " << numCorrect << endl;
cout << "Number of incorrect answers: " << numIncorrect << endl;
cout << "Quiz percentage: " << (numCorrect * 100.0 / possibleCorrect) << "%" << endl;
cout << endl;
return 0;
}
For this purpose though, a simple if/else would be easier to read:
int problem4() {
int numCorrect = 0;
int numIncorrect = 0;
int possibleCorrect = 4;
int correctAnswerOne = 120;
int correctAnswerTwo = 65536;
int correctAnswerThree = 18;
int correctAnswerFour = 11;
int guessOne;
int guessTwo;
int guessThree;
int guessFour;
cout << "*** Start of problem 4 ***" << endl;
cout << "Welcome to our math quiz program!" << endl;
cout << "Please enter the answers to the following questions: " << endl;
cout << "5! = ";
cin >> guessOne;
cout << "(2^(2^(2^2))) = ";
cin >> guessTwo;
cout << "3 * (4 + 8) / ((4 * 2) / (5 - 1)) = ";
cin >> guessThree;
cout << "3 + 2 + 1 + 2 + 3 = ";
cin >> guessFour;
if( guessOne == 120 ) ++numCorrect; else ++numIncorrect;
if( guessTwo == 65536 ) ++numCorrect; else ++numIncorrect;
if( guessThree == 18 ) ++numCorrect; else ++numIncorrect;
if( guessFour == 11 ) ++numCorrect; else ++numIncorrect;
cout << "Number of correct answers: " << numCorrect << endl;
cout << "Number of incorrect answers: " << numIncorrect << endl;
cout << "Quiz percentage: " << (numCorrect * 100.0 / possibleCorrect) << "%" << endl;
cout << endl;
return 0;
}
Related
I am new to the coding community and I am here to ask on how can I store the calculations that have been done in my calculator. I am currently new in this space and I am currently looking for answers T-T.
my code goes like this thank you everyone! T-T pls be gentle on me.
#include<iostream>
#include<stdlib.h>
using namespace std;
int calculator();
void history();
void choice();
int main()
{
int x;
cout << "\t\t\t\tWhat do you want to do?\n\n";
cout << "\t\t\t\t[1] Standard calculator\n";
cout << "\t\t\t\t[2] History\n";
cout << "\t\t\t\t[3] Exit\n\n\n\n";
cout << "\t\t\t\tChoice: ";
cin >> x;
switch (x)
{
case 1:
calculator();
break;
case 2:
history();
break;
case 3:
cout << "\n\n\nThank you for using my calculator!";
exit(4);
break;
default:
cout << "Enter a correct choice";
main();
}
}
int calculator()
{
double x, y;
float sum = 0.0, dif = 0.0, prod = 1.0, quo = 1.0;
int i;
char op, back;
do {
system("CLS");
cout << "\t\t#CALCULATOR#" << endl;
cout << endl << endl;
cout << "Calculate 2 numbers: (example 1 + 1 or 2 * 2)\n";
cin >> x >> op >> y;
switch (op) {
case '+':
sum = x + y;
cout << "The sum of " << x << " and " << y << " is " << sum;
break;
case '-':
dif = x - y;
cout << "The difference of " << x << " and " << y << " is " << dif;
break;
case '*':
prod = x * y;
cout << "The product of " << x << " and " << y << " is " << prod;
break;
case '/':
if (y == 0)
cout << "Undefined";
else
quo = x / y;
cout << "The quotient of " << x << " and " << y << " is " << quo;
break;
default:
cout << "Invalid operator";
break;
}
cout << "\nContinue[Y/N]: ";
cin >> back;
cout << endl << endl;
if (back != 'Y' && back != 'y' && back != 'N' && back != 'n')
{
cout << "Please enter a correct choice" << endl;
choice();
}
else if (back == 'N' || back == 'n')
{
system("pause");
system("CLS");
main();
}
} while (back == 'y' || back == 'Y');
cout << "Thank you";
system("pause");
system("CLS");
}
void choice()
{
char c;
do
{
cout << "Do you want to continue? [Y/y or N/n]" << endl;
cin >> c;
if (c == 'Y' || c == 'y')
calculator();
else if (c == 'N' || c == 'n')
{
system("pause");
system("cls");
main();
}
else
cout << "Please enter a correct choice\n";
choice();
} while (c != 'y' || c != 'Y' || c != 'N' || c != 'n');
cout << "Enter a correct choice";
}
void history()
{
cout << "I still dont know how T - T";
}
I wanted to store the past calculations using arrays but i dont know how to actually put it in my code T-T pls help
You want to #include <vector> and make a history std::vector, that holds strings:
std::vector<std::string> history;
When you do the calculcation, don't output to cout, but to a std::ostringstream first (located in <sstream>):
std::ostringstream caclulation_stream;
switch (op) {
case '+':
sum = x + y;
caclulation_stream << "The sum of " << x << " and " << y << " is " << sum;
break;
case '-':
dif = x - y;
caclulation_stream << "The difference of " << x << " and " << y << " is " << dif;
break;
case '*':
prod = x * y;
caclulation_stream << "The product of " << x << " and " << y << " is " << prod;
break;
case '/':
if (y == 0)
caclulation_stream << "Undefined";
else
quo = x / y;
caclulation_stream << "The quotient of " << x << " and " << y << " is " << quo;
break;
default:
caclulation_stream << "Invalid operator";
break;
}
this way, you can save the string to history. push_back() adds the string to the vector. Don't forget to also print out the string, so it's still displayed in the console.
auto calculation_string = caclulation_stream.str();
history.push_back(calculation_string);
std::cout << calculation_string;
to display the history, you can loop over the vector and print out the elements:
void show_history()
{
for (const auto& entry : history) {
std::cout << entry << '\n';
}
}
this should give you the basic ideas on how to implement this.
Read here why you shouldn't be using namespace std;.
Simple mathgame.cpp.
case(2) is the subtraction of two random integers, but the **results cant be less than 0.
** I need 'subOp' to only hold the values of 'ranNum1' - 'ranNum2' when they equal >= 0
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
// Initialize random number generator.
srand(time(0));
// Declares variable as a random integer between 0-12
// int ranNum1 = rand() % 13;
// int ranNum2 = rand() % 13;
int menuChoice = 0;
int userAns=0;
// String variable for the game menu
string mathMenu =
"\n\n\tMATH GAME SELECTION\n\t-------------------\n\t1) Addition\n"
"\t2) Subtraction\n\t3) Multiplication\n\t4) -EXIT-\n";
// Answer responses
string cAns = "\n\tCORRECT ANSWER!" , wAns = "\n\tWRONG ANSWER!";
// While the user doesnt request to exit...
while (menuChoice != 4)
{
int ranNum1 = rand() % 13;
int ranNum2 = rand() % 13;
switch (menuChoice)
{
case (0):
break;
case (1): { int addOp = ranNum1 + ranNum2;
cout << "\tWhat is " << ranNum1 << " + " << ranNum2 << " = [?]\n \tYour answer: ";
cin >> userAns;
if (userAns == addOp) {
cout << cAns; }
else{
cout << wAns << "\n\tThe correct answer was " << addOp; }
break; }
case (2): { int subOp = ranNum1 - ranNum2;
do {
cout << "\tWhat is " << ranNum1 << " - " << ranNum2 << " = [?]\n\tYour answer: ";
cin >> userAns;
if (userAns == subOp) {
cout << cAns;
}
else {
cout << wAns << "\n\tThe correct answer was " << subOp;
}
} while (subOp < 0);
break; }
case (3):{ int multOp = ranNum1 * ranNum2;
cout << "\tWhat is " << ranNum1 << " x " << ranNum2 << " = [?]\n \tYour answer: ";
cin >> userAns;
if (userAns == multOp) {
cout << cAns; }
else {
cout << wAns << "\n\tThe correct answer was " << multOp; }
break; }
//Error message/ validator for integers between 1-4.
default: cout << "\t**Invalid menu selection** \n\a";
}
//Error message/ validator for input other than integer.
cout << mathMenu << endl << " Please Select An Option (1-4): ";
while (!(cin >> menuChoice)) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Please ONLY select the given options (1-4): \a";
}
cout << endl;
}
system("pause");
return 0;
}
I've tried several different loops and bools. How do I loop through the equation until the results will only equal >0?
You can make a conditional statement to check whether the second value is greater than the first one. If so, then swap between them.
if (ranNum1 < ranNum2)
std::swap(ranNum1, ranNum2);
int subOp = ranNum1 - ranNum2;
Now, the value of ranNum1 is always greater than ranNum2.
I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C++ so I'm still learning and this code is not completed yet but can anyone please help me with this?
int main()
{
// Declare Constant variables
const float DISC_GOLF_RETAIL = 14.96;
const float ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const float DISCOUNT2 = .16;
const float DISCOUNT3 = .24;
const float DISCOUNT4 = .32;
const double DEC = 100;
// Declare variables
double quantity;
double pricePerDisc;
double totalSavings;
double total;
char userInput;
float discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
// Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
// Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (discType)
{
case 1: userInput=='u' || 'U';
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
break;
case 2: userInput=='g' || 'G';
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
cout << "------------Receipt------------" << endl;
if (quantity>5 && quantity<=9)
{
discount = DISCOUNT1 / DEC;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>10 && quantity<=19)
{
discount = DISCOUNT2;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>20 && quantity<=29)
{
discount = DISCOUNT3;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>= 30)
{
discount = DISCOUNT4;
}
totalSavings = (pricePerDisc * quantity) * discount;
total = quantity * pricePerDisc - totalSavings;
cout << "Disc Type: " << discType << endl;
cout << "Quantity: " << quantity << endl;
cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
<< pricePerDisc << endl;
cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
<< totalSavings << endl;
cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
For single char responses, you can use the switch/case statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string is usually consists of more than one character.
I'm trying to output the score for each addition, subtraction, multiplication, division in the end test function. and the total of the question asked.
**Any help would be appreciated
BTW this is only using local functions and is passing the scores by reference. IT's supposed to output the number of answers that you answer correctly.
Also is there a way where you can prevent the program from letting you select the choices more than once?
here's what I got so far:
#include < iostream >
#include < iomanip >
#include < stdlib.h >
#include < time.h >
#include < stdlib.h >
using namespace std;
int addition(int addscore);
int subtraction(int subscore);
int multiplication(int multiscore);
int division(int divscore);
int endtest(int & addscore, int & subscore, int & multiscore, int & divscore);
main() {
int end_final = 0;
do {
int addscore, subscore, multiscore, divscore;
char choice;
cout << "A- " << "Addition\n";
cout << "B- " << "Subtraction\n";
cout << "C- " << "Multiplication\n";
cout << "D- " << "Division\n";
cout << "E- " << "End of Test\n";
cin >> choice;
cout << endl << endl;
switch (choice) {
case 'A':
case 'a':
addition(addscore);
break;
case 'B':
case 'b':
subtraction(subscore);
break;
case 'C':
case 'c':
multiplication(multiscore);
break;
case 'D':
case 'd':
division(divscore);
break;
case 'E':
case 'e':
endtest(addscore, subscore, multiscore, divscore);
break;
}
}
while (end_final != 1);
return 0;
}
int addition(int addscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
int total = 0;
for (int i = 1; i <= 5; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
addscore++;
} else {
cout << "Incorrect \n";
}
}
}
int subtraction(int subscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen subtraction\n";
int randnum1, randnum2;
int total = 0;
while (total != 5) {
randnum1 = rand() % 20 + 1;
randnum2 = rand() % 20 + 1;
if (randnum1 >= randnum2) {
cout << randnum1 << " " << "-" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 - randnum2) {
cout << endl;
cout << "Correct!\n ";
subscore++;
} else {
cout << "Incorrect\n ";
}
}
}
}
int multiplication(int multiscore) {
int iRandom;
int total = 0;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen Multiplication\n";
int randnum1, randnum2;
for (int i = 1; i <= 5; i++) {
randnum1 = rand() % 20 + 1;
randnum2 = rand() % 20 + 1;
cout << randnum1 << " " << "x" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 * randnum2) {
cout << endl;
cout << "Correct! \n";
multiscore++;
} else {
cout << "Incorrect\n ";
}
}
}
int division(int divscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen Division\n";
int randnum1, randnum2;
int total = 0;
while (total != 5) {
randnum1 = rand() % 13 + 1;
randnum2 = rand() % 13 + 1;
if (randnum1 % randnum2 == 0) {
cout << randnum1 << " " << "/" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 / randnum2) {
cout << endl;
cout << "Correct! \n";
divscore++;
} else {
cout << "Incorrect\n ";
}
}
}
}
int endtest(int & addscore, int & subscore, int & multiscore, int & divscore) {
int total = 0;
cout << endl << endl;
cout << "Addition" << " " << addscore++ << endl;
cout << "Subtraction" << " " << subscore << endl;
cout << "Multiplication" << " " << multiscore << endl;
cout << "Division" << " " << divscore << endl;
cout << "Total" << " " << total << endl;
}
To clarify the code, declare an enum
enum { ADDITION=0, SUBTRACTION, MULTIPLICATION, DIVISION };
You could have global arrays
int used[] = { 0,0,0,0 }; // not used
int total[] = { 0,0,0,0 }; // total questions per operation
int score[] = { 0,0,0,0 }; // score per operation
Then, doing it for 'addition', in the do {
if ( ! used[ADDITION]) cout << "A- " << "Addition\n";
then in the switch
case 'A':
case 'a':
used[ADDITION] = 1; // tells addition was used
addition(addscore);
break;
The addition code becomes
int addition(int addscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
total[ADDITION] = 0; // should not be
score[ADDITION] = 0; // ...necessary (but in case you call it again)
for (int i = 0; i < 5 ; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total[ADDITION]++; // total is incremented for Addition
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
score[ADDITION]++; // score is incremented
} else {
cout << "Incorrect \n";
}
}
}
endtest becomes
int endtest() {
cout << endl << endl;
if (used[ADDITION]) cout << "Addition" << " " << score[ADDITION] << " / " << total[ADDITION] << endl;
// same for SUBTRACTION ...
int grandtotal = total[ADDITION] + ....;
cout << "Grand Total" << " " << grandtotal << endl;
}
endtest is declared, and called like that
int endtest();
...
endtest();
Since this is C++, you could also make a class Operation, then one subclass per operation, holding the name of the operation and overriding a 'execute' method that does the specific operation, then declare an array of the parent class that holds an instance of each operation ...
Based on OP's comments, after the do {
// initialize variables to zero
int addscore=0, subscore=0, multiscore=0, divscore=0;
in the switch
case 'A':
case 'a':
used[ADDITION] = 1; // tells addition was used
addition( &addscore ); // <== gives the pointer to that variable
break;
then in addition code
int addition(int *addscore) { // <== gets a pointer
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
total[ADDITION] = 0; //
score[ADDITION] = 0; // using your way, this is not necessary anymore
for (int i = 0; i < 5 ; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total[ADDITION]++; // total is incremented for Addition
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
// score[ADDITION]++; // score is incremented (see above)
*addscore++; // <== increment variable pointed to by pointer
} else {
cout << "Incorrect \n";
}
}
}
The intent is to ask a user if they want to play, output options, receive userinput and then simulate a 'roll' the appropriately sided dice. Output the results, and then ask for another choice, etc.
The first cycle of the program works as it should, but instead of it asking if you want to play again it is blank. If you enter a number to select the dice it will output how many sides the first dice had no matter what is chosen.
#include <iostream>
#include <ctime>
using namespace std;
int throwDie(int Sides, int &throwResult)
{
throwResult = 1 + rand() % (Sides - 1 + 1);
return throwResult;
}
int main()
{
int dieTot = 0,
throwNumber = 0,
numberSides = 0,
throwResult = 0;
int die1 = 4;
int die2 = 6;
int die3 = 8;
int die4 = 10;
int die5 = 12;
int die6 = 20;
char rollAgain;
srand(unsigned(time(0) ));
START:
cout << "Do you want Play? ";
cin >> rollAgain;
cout << "How many sides? " << endl;
cout << "1 - 4 sided die\n";
cout << "2 - 6 sided die\n";
cout << "3 - 8 sided die\n";
cout << "4 - 10 sided die\n";
cout << "5 - 12 sided die\n";
cout << "6 - 20 sided die\n";
int choice;
cout << "Enter choice: ";
cin >> choice;
switch( choice ) {
case 1:
do {
cout << "You have choosen a 4 sided die? " << endl;
int numberSides = die1;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
} while (choice != numberSides );
goto START;
break;
case 2:
do {
cout << "You have choosen a 6 sided die? " << endl;
int numberSides = die2;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
} while (choice != numberSides );
break;
case 3:
do {
cout << "You have choosen a 8 sided die? " << endl;
int numberSides = die3;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
} while (choice != numberSides );
break;
case 4:
do {
cout << "You have choosen a 10 sided die? " << endl;
int numberSides = die4;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
} while (choice != numberSides );
break;
case 5:
do {
cout << "You have choosen a 12 sided die? " << endl;
int numberSides = die5;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
} while (choice != numberSides );
break;
case 6:
do {
cout << "You have choosen a 20 sided die? " << endl;
int numberSides = die6;
cout << numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
} while (choice != numberSides );
break;
default:
cout << "Not a proper entry.\n";
break;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
return 0;
}
}
I am assuming the extra code in each of the case statments is:
cout << numberSides << "-sided die rolled for a value of " << throwDie(numberSides, throwResult) << "!" << endl;
dieTot = dieTot + throwResult;
throwNumber++;
cin >> numberSides;
cout << endl << "Total for " << throwNumber << " throws = " << dieTot << endl;
}
while (choice != numberSides );
break;
Would that go at the end of the code? Not in every case statement. Also if I do that would I even need to put the while/do into functions?
This has nothing do with looping.
Try printout out the values obtained from your cin's and you'll see the problem.
You use your goto statement inconsistently, you only return to START in your first case
You don't properly terminate your switch statement
You should just about never use a goto unless you can't do it any other way.
This is horribly written. Why do you need to duplicate everything in each case statement? Seems like you only need to use the switch for setting the value of numberSides and the print out.. The rest should be common... I don't think you need the variables either... see my raw refactor just of your code to simply things...
Refactoring your code makes it much more readable: see below
#include <iostream>
#include <ctime>
using namespace std;
//This function will throw a dice returning the result while updating the parameter.
int throwDie(int Sides, int &throwResult)
{
throwResult = 1 + rand() % (Sides); //Sides - 1 + 1 == Sides
return throwResult;
}
//Display the menu
void displayMenu()
{
cout << "How many sides? \n"
<< "1 - 4 sided die\n"
<< "2 - 6 sided die\n"
<< "3 - 8 sided die\n"
<< "4 - 10 sided die\n"
<< "5 - 12 sided die\n"
<< "6 - 20 sided die\n"
<< "CTRL-D to quit";
}
int main()
{
int dieTot = 0,
throwNumber = 0,
numberSides = 0,
throwResult = 0;
// THESE ARENT NEEDED
// sides = 4+2*(X-1)
//int die1 = 4;
//int die2 = 6;
//int die3 = 8;
//int die4 = 10;
//int die5 = 12;
//int die6 = 20;
srand(unsigned(time(0) ));
displayMenu();
int choice;
while ( cin >> choice ) {
/* cin >> choice will return 0 / fail if they enter CTRL-D or enter
something other than a number... you'll have to handle that in another way */
if ( choice < 1 || choice > 6 ) {
cout << "Invalid choice try again!";
continue;
}
//numberSides = 4+2*(choice-1); //fast way
switch (choice) {
case 6:
numberSides = 20;
break;
case 1:
//if you dont want to do this slick trick of fall through
//numberSides = 4;
//break;
case 2:
case 3:
case 4:
case 5:
numberSides = 4+2*(choice-1); // use this for 1,2,3,4,5;
break;
}
cout << "You have chosen a " << numberSides << " sided die.\n"
<< numberSides << "-sided die rolled for a value of "
<< throwDie(numberSides, throwResult) << "!" << endl;
dieTot += throwResult;
throwNumber++;
}
cout << "\n\n" << "Total for " << throwNumber << " throws = " << dieTot << endl;
return 0;
}