"0" appearing after function is completed in C++ - c++

// This program is able take two variables`
// and apply Auto increment or decrement`
// based on the user's input and by calling a function
#include <iostream>
using namespace std;
int inc (int, int); // Increment function prototype
int dec (int, int); // Decrement function prototype
int main ()
{
int num1, num2;
char operation = ' ', I, D;
cout << "Enter the first variable: ";
cin >> num1;
cout << "Enter the second variable: ";
cin >> num2;
cout << endl;
cout << "Do you want Auto increment, decrement or both? (Type 'I', 'D' or 'B'): ";
cin >> operation;
if (operation == 'I') {
cout << inc(num1,num2);
}
else if (operation == 'D') {
cout << dec(num1,num2);
}
else if (operation == 'B') {
cout << inc(num1,num2);
cout << endl;
cout << dec(num1,num2);
}
else {
cout << "Error please enter 'I', 'D' or 'B' as a option" << endl;
}
return 0;
}
int inc (int num1, int num2) {
num1++; num2++;
cout << "Number 1 ++ is: " << num1 << endl;
cout << "Number 2 ++ is: " << num2 << endl;
return 0;
}
int dec (int num1, int num2) {
--num1; --num2;
cout << "Number 1 -- is: " << num1 << endl;
cout << "Number 2 -- is: " << num2 << endl;
return 0;
}
I just started taking Fundamentals of programming I at college and i have this assignment and this 0 keeps appearing after the function has completed

This happens because your inc and dec print stuff, but also return an int. You then proceed to print the return value, on these lines:
cout << inc(num1,num2);
and
cout << dec(num1,num2);
.
You can safely remove these cout << prefixes, and probably the entire return value, as it does not seem necessary to output your resuls (that happens in inc and dec).

int inc (int &num1, int &num2)
int dec (int &num1, int &num2)
Don't forget the ampersand to modify globalvariables

if (operation == 'I') {
cout << inc(num1,num2);
}
else if (operation == 'D') {
cout << dec(num1,num2);
}
else if (operation == 'B') {
cout << inc(num1,num2);
cout << endl;
cout << dec(num1,num2);
}
In this section don't use cout. The function is returning 0 and you are printing it using cout << dec(num1,num2);.
Just call the function as you are printing the values inside the function.
if (operation == 'I') {
inc(num1,num2);
}
else if (operation == 'D') {
dec(num1,num2);
}
else if (operation == 'B') {
inc(num1,num2);
cout << endl;
dec(num1,num2);
}
And also as if you want to modify num1 and num2 inside the functions so that the variables declared in main function is modified also, then you have to pass by reference like:
int inc (int &num1, int &num2) {
num1++; num2++;
cout << "Number 1 ++ is: " << num1 << endl;
cout << "Number 2 ++ is: " << num2 << endl;
return 0;
}
int dec (int &num1, int &num2) {
--num1; --num2;
cout << "Number 1 -- is: " << num1 << endl;
cout << "Number 2 -- is: " << num2 << endl;
return 0;
}

Related

Math tutor program troubles

Hello once again stack overflow users! I have a new program, and have once again ran into a bit of a problem I cannot figure out! I wrote a program, math tutor program, which is practically finished, just that there are a few things I cannot figure out. In the program, there is a void function that checks the answers (will display if user input is correct or incorrect) but I cant seem to get it to work. When I have it in my doOneSet void function (does exactly one set or problems) it seems to only display "incorrect" even though the answer is correct? I cant seem to figure out what I did wrong or what is missing. Any type of help/tips/references is appreciated. Thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void getProbsPerSet (int& numProbs);
void printHeader (/*in*/ char problemType);
void getMaxNum(/* out */int& maxNum);
void generateOperands(int& num1, int& num2, int maxNum);
void checkAnswer (/* in */int num1,/* in */ int num2, /*out*/ int& answer);
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer);
void doOneProblem (char problemType, int maxNum);
void doOneSet (char problemType, int probsPerSet, int&);
void printReport (/* in */ int probsPerSet, int& set1Correct, /* in */int& set2Correct, /* in */int& set3Correct);
int main ()
{
int set1Correct, set2Correct, set3Correct, probsPerSet, maxNum;
srand(time(0));
getProbsPerSet (probsPerSet);
cout << endl;
doOneSet ('+', probsPerSet, set1Correct);
cout << endl;
doOneSet ('-', probsPerSet, set2Correct);
cout << endl;
doOneSet ('*', probsPerSet, set3Correct);
cout << endl;
return 0;
}
void getProbsPerSet (int& numProbs)
{
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
while (numProbs < 3 || numProbs > 10)
{
cout << endl;
cout << "Please stay between 3 and 10. Thank you!";
cout << endl;
cout << endl;
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
}
}
void printHeader (/*in*/ char problemType)
{
switch(problemType)
{
case '+': cout << endl;
cout << "Set # 1" << endl;
cout << "----------" << endl;
break;
case '-': cout << endl;
cout << "Set # 2" << endl;
cout << "----------" << endl;
break;
case '*': cout << endl;
cout << "Set # 3" << endl;
cout << " ----------" << endl;
break;
}
}
void doOneProblem (char problemType, int maxNum)
{
int num1,num2,answer;
generateOperands(num1, num2, maxNum);
switch (problemType)
{
case '+' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '-' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '*' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
}
}
void doOneSet (char problemType, int probsPerSet, int& answer)
{
int num1, num2, numProbs, maxNum;
bool isCorrect;
printHeader(problemType);
getMaxNum(maxNum);
for (int count = 0; count < probsPerSet; count++)
{
generateOperands(num1, num2, maxNum);
doOneProblem (problemType, maxNum);
calcCorrectAnswer(problemType, num1, num2, answer);
checkAnswer (num1, num2, answer);
}
}
void generateOperands(int& num1, int& num2, int maxNum)
{
num1 = 1 + rand() % maxNum;
num2 = 1 + rand() % maxNum;
}
void getMaxNum(/*out*/ int& maxNum)
{
cout << "What is the maximum number for this set?: ";
cin >> maxNum;
}
void checkAnswer (int num1, int num2, /*out*/ int& answer)
{
bool isCorrect;
if (answer == isCorrect)
{
cout << endl;
cout << "Correct!" << endl;
cout << endl;
}
else
{
cout << endl;
cout << "Incorrect!" << endl;
cout << endl;
}
}
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer)
{
bool isCorrect;
switch (problemType)
{
case '+' : isCorrect = num1 + num2;
break;
case '-' : isCorrect = num1 - num2;
break;
case '*' : isCorrect = num1 * num2;
break;
}
}
void printReport (/* in */ int probsPerSet, int& set1Correct, /*in*/ int& set2Correct, /*in*/ int& set3Correct)
{
int set1Percent = 0, set2Percent = 0, set3Percent = 0;
int total, complete;
int numcorrect = 1;
total = set1Correct + set2Correct + set3Correct;
complete = probsPerSet + probsPerSet + probsPerSet;
set1Percent = (100 * set1Correct) / probsPerSet;
set2Percent = (100 * set2Correct) / probsPerSet;
set3Percent = (100 * set3Correct) / probsPerSet;
cout << endl;
cout << "Set #1 : You got " << set1Correct << " correct out of " << probsPerSet << " for " << set1Percent << "%" << endl;
cout << "Set #2 : You got " << set2Correct << " correct out of " << probsPerSet << " for " << set2Percent << "%" << endl;
cout << "Set #3 : You got " << set3Correct << " correct out of " << probsPerSet << " for " << set3Percent << "%" << endl;
cout << endl;
cout << "Overall you got " << total << " out of " << complete << endl;;
}
The problem is your bool isCorrect;. Both of them. 😎
So, in one function, calcCorrectAnswer, you declare this variable, then set it according to the logic of your requirements. Fine.
Then in another function, checkAnswer, you declare it again, then compare it to true/false to choose which output to produce.
But these are different variables. Despite sharing a name, they are scoped to the function they're in, so setting one has no effect on the other. The one in checkAnswer is uninitialised and never takes a value, so your program has undefined behaviour.
You could return your boolean from calcCorrectAnswer and pass it as an argument to checkAnswer. Or you could just merge those two functions; there doesn't seem to be a big reason to keep them separate.

If/else loops: C++ Program: Won't display final prompt/final loop

I'm having a lot of trouble with this assignment for my first C++ course.
I have figured out how to get it to properly ask the user what operation they would like to use (add, subtract, multiply), generate random numbers between 0-9, and how to ask the user to solve the problem and respond if it is correct or incorrect.
After this point, the program is supposed to ask the user if they would like to continue (by pressing y) or quit (by pressing Q), with an error message for the user when they enter any other letter, but for some reason this part doesn't display when running the program.
How do I get the loop to work correctly, allowing me to do the final prompt, and THEN repeat the whole program only when pressing Y or quit when pressing Q?
Note: I'm VERY new to coding in general, and this is my very first C++ course, so I do not know yet how to make this code more succinct:
#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
while (true)
{
// Generate two random single-digit integers btwn 0-9
srand(time(0));
int num1 = rand() % 10;
int num2 = rand() % 10;
int operation, play, num3, guess, Y, Q;
// If num1 < num2, swap num1 with num2
if (num1 < num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
}
cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cin >> operation;
if (operation > 3 || operation < 1)
{
cout << "Your operation choice isn't valid! Please try again, using 1, 2, or 3." << endl;
cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cin >> operation;
}
else if (operation == 1)
{
cout << "You chose addition." << endl;
num3 = num1 + num2;
cout << "What is " << num1 << " + " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
cout << "What is " << num1 << " + " << num2 << " ?: " << endl;
cin >> guess;
}
else if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
}
else if (operation == 2)
{
cout << "You chose subtraction." << endl;
num3 = num1 + num2;
cout << "What is " << num1 << " - " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
cout << "What is " << num1 << " - " << num2 << " ?: " << endl;
cin >> guess;
}
else if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
}
else if (operation == 3)
{
cout << "You chose multiplication." << endl;
num3 = num1 * num2;
cout << "What is " << num1 << " * " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
cout << "What is " << num1 << " * " << num2 << " ?: " << endl;
cin >> guess;
}
else if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
}
while (guess != num3)
{
int play, Y, Q;
cout << "Would you like to play again? Press Y for yes or Q for
quit" << endl;
cin >> play;
if (play != Y || play != Q)
{
cout << "That is not a valid choice. Please choose Y for yes
or Q to quit. " << endl;
cin >> play;
}
else
{
if (play == Y)
{
cout << "Thank you for playing! Let's play again!" << endl;
cout << "" << endl;
}
else if (play == Q)
{
cout << "Thank you for playing! See you next time!" << endl;
cout << "" << endl;
}
break;
}
}
}
return 0;
}
There are few things here...
1. Only seed once
Move srand(time(0)); out of the while loop and to the top of main. If you repeatedly seed in the same second (if time(0) doesn't change), you'll get the same "random" numbers twice.
2. What happens to num3 if they don't enter a valid operation?
You never initalize num3, so if they don't choose a valid operation, num3 will have a junk value. You then go on to run a loop whose condition depends on num3's value! (while (guess != num3))
3. else { ... if { is the same as else if {
In your final loop, bring the if (play == Y) and else if (play == Q) out of that nested if and make them else if's.
4. Your last loop condition is incorrect
Is while (guess != num3) really right? You want to loop until they enter valid input, so why are you looping while guess != num3?
The problem is found with in the second while-loop. The play variable should be declared as a char rather than an int. Plus you don't need to compare it with Y and Q integer variables. Here is a solution. I hop it will help you:
#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
bool loop = true;
while (loop)
{
// Generate two random single-digit integers btwn 0-9
srand(time(0));
int num1 = rand() % 10;
int num2 = rand() % 10;
int operation, play, num3, guess, Y, Q;
// If num1 < num2, swap num1 with num2
if (num1 < num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
}
cout << "Choose an operation.\n\t-----------------------" << endl;
cout << "\tEnter 1 to add,\n\tEnter 2 to subtract, or\n\tEnter 3 to multiply\n\t-----------------------\n\t\tEnter: ";
cin >> operation;
if (operation > 3 || operation < 1)
{
cout << "Invalid choice! Please try again." << endl;
continue;
}
else if (operation == 1)
{
cout << "You chose addition." << endl;
num3 = num1 + num2;
cout << "What is " << num1 << " + " << num2 << " = ";
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "What is " << num1 << " + " << num2 << " = ";
cin >> guess;
}
else if (guess == num3)
cout << "That is correct!" << endl;
}
else if (operation == 2)
{
cout << "You chose subtraction." << endl;
num3 = num1 + num2;
cout << "What is " << num1 << " - " << num2 << " = ";
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "What is " << num1 << " - " << num2 << " = ";
cin >> guess;
}
else if (guess == num3)
cout << "That is correct!" << endl;
}
else if (operation == 3)
{
cout << "You chose multiplication." << endl;
num3 = num1 * num2;
cout << "What is " << num1 << " * " << num2 << " = ";
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "What is " << num1 << " * " << num2 << " = ";
cin >> guess;
}
else if (guess == num3)
cout << "That is correct!" << endl;
}
while (true)
{
char play;
cout << "Would you like to play again? Press Y for yes or Q for quit: ";
cin >> play;
if (play == 'Y' || play == 'y')
break;
else if(play == 'Q' || play == 'q')
{
loop = false;
cout << "Good bye.\n";
break;
}
else
cout<< "Invalid choice.\n";
}
}
return 0;
}
Making the menu a little interactive is also good, peace.
It's could be better to use a switch case to select the correct operation like this:
Switch(operation) {case 1: break;}
You need to add one more while too
SO the correct code should be like this:
#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int operation, num3, guess,num1,num2,temp;
srand(time(0));
char play;
do
{
// Generate two random single-digit integers btwn 0-9
num1 = rand() % 10;
num2 = rand() % 10;
// If num1 < num2, swap num1 with num2
if (num1 < num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
do
{
cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cin >> operation;
if (operation > 3 || operation < 1)
{
cout << "Your operation choice isn't valid! Please try again, using 1, 2, or 3." << endl;
cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cin >> operation;
}
}while(operation>3 || operation<1);
switch(operation)
{
case 1:
cout << "You chose addition." << endl;
num3 = num1 + num2;
do
{
cout << "What is " << num1 << " + " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
}while(guess!=num3);
cout << "That is correct!" << endl;
cout << "" << endl;
break;
case 2:
cout << "You chose subtraction." << endl;
num3 = num1 - num2;
do
{
cout << "What is " << num1 << " - " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
}while(guess!=num3);
cout << "That is correct!" << endl;
cout << "" << endl;
break;
case 3:
cout << "You chose multiplication." << endl;
num3 = num1 * num2;
do
{
cout << "What is " << num1 << " * " << num2 << " ?: " << endl;
cin >> guess;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
}while(guess!=num3);
cout << "That is correct!" << endl;
cout << "" << endl;
break;
}
do
{
cout << "Would you like to play again? Press Y for yes or Q for quit" << endl;
cin >> play;
if (play != 'Y' && play != 'Q')
{
cout << "That is not a valid choice. Please choose Y for yes or Q to quit. " << endl;
}
}while(play!='Y' && play!='Q');
if (play == 'Y')
{
cout << "Thank you for playing! Let's play again!" << endl;
cout << "" << endl;
}
else
{
cout << "Thank you for playing! See you next time!" << endl;
cout << "" << endl;
}
}while(play=='Y');
return 0;
}
Solution:
P29: Practice Arithmetic Skills (if/else , loop)
Description:
"Write a program to let a child practice arithmetic skills.
The program should first ask for what kind of practice is wanted: +, -, * , and let the user repeat the practice as many times as desired, until "Q" is entered.
Two random numbers will be generated from (0 - 9).
If the child answers the equation correctly, a message should appear , and they can then go to the next problem(two different numbers generated).
If the child answers incorrectly, a message should appear & the problem should be repeated (same numbers used)."
Finally fixed!:
#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int operation, num3, guess, num1, num2, temp;
char play;
srand(time(0));
do
{
num1 = rand() % 10;
num2 = rand() % 10;
if (num1 < num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
do
{
cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cout << "" << endl;
cin >> operation;
if (operation > 3 || operation < 1)
{
cout << "Your operation choice isn't valid! Please try again, using 1, 2, or 3." << endl;
}
}while (operation > 3 || operation < 1);
switch(operation)
{
case 1:
cout << "You chose addition." << endl;
num3 = num1 + num2;
cout << "" << endl;
do
{
cout << "What is " << num1 << " + " << num2 << " ?: " << endl;
cout << "" << endl;
cin >> guess;
cout << "" << endl;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
} while (guess != num3);
if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
break;
case 2:
cout << "You chose subtraction." << endl;
num3 = num1 - num2;
cout << "" << endl;
do
{
cout << "What is " << num1 << " - " << num2 << " ?: " << endl;
cout << "" << endl;
cin >> guess;
cout << "" << endl;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
} while (guess != num3);
if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
break;
case 3:
cout << "You chose multiplication." << endl;
num3 = num1 * num2;
cout << "" << endl;
do
{
cout << "What is " << num1 << " * " << num2 << " ?: " << endl;
cout << "" << endl;
cin >> guess;
cout << "" << endl;
if (guess != num3)
{
cout << "That is incorrect. Please try again." << endl;
cout << "" << endl;
}
} while (guess != num3);
if (guess == num3)
{
cout << "That is correct!" << endl;
cout << "" << endl;
}
break;
}
do
{
cout << "Would you like to play again? Press Y for yes or Q for quit" << endl;
cout << "" << endl;
cin >> play;
if (play != 'Y' && play != 'Q')
{
cout << "That is not a valid choice. Please choose Y for yes or Q to quit. " << endl;
cout << "" << endl;
}
}
while(play !='Y' && play !='Q');
if (play == 'Y')
{
cout << "Thank you for playing! Let's play again!" << endl;
cout << "" << endl;
}
else
{
cout << "Thank you for playing! See you next time!" << endl;
cout << "" << endl;
}
}
while(play=='Y');
return 0;
}

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}

Score component in beginner C++ program

I am doing an assignment where I am supposed to write a program to test the user's math skills. Here's the code i have right now:
using namespace std;
void addition()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " + " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value+Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value+Value2 << "." << endl << endl;
}
}
}
}
}
void substraction()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " - " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value-Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value-Value2 << "." << endl << endl;
}
}
}
}
}
void Multiplication()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " x " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value*Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value*Value2 << "." << endl << endl;
}
}
}
}
}
int main()
{
int number;
cout << "Enter the number for the problem type desired:"<<endl;
cout << " 1. Addition"<<endl;
cout << " 2. Subtraction"<<endl;
cout << " 3. Multiplication"<<endl;
cin >> number;
if (number == 1)
{
addition();
}
else if(number == 2)
{
substraction();
}
else if (number ==3)
{
Multiplication();
}
}
The program runs fine. However, there should be a score component where the user gets 10 points on the first try, 5 point on second try, and 0 on third try/wrong. I have no idea how to blend the score component in and the display at the end of 10 questions. Hints please?
All thanks in advance.
You should keep a score variable in each of your functions, add to the score variable as necessary and then return the score variable.
So those function are no longer going to be voids, they'll be ints. You can then get the score at the end and print it out.
I'm not going to write any code for you, since it is for an assignment :P

How do I loop to the top in C++? Could you show me an example?

I'm trying to make my calcuator loop back to the top after it finishes the calculation? I've tried while loops and seen tutorials on it but I just can't put it into context.
If you could show me how to actually use it in this program, that would be fantastic.
#include<iostream>
using namespace std;
int main() {
double num1, num2;
char op;
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)\n" << endl;
cin >> op;
cout << "Please enter your second number\n" << endl;
cin >> num2;
if (op== '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!" << endl;
}
}
I think you want anything like this:
#include<iostream>
using namespace std;
int main() {
double num1 = 0, num2 = 0;
char op = '';
char answer = '';
while(answer != 'n') { // Check condition
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)" << endl;
cin >> op;
cout << "Please enter your second number\n" << endl;
cin >> num2;
if (op == '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!\n Exit." << endl;
}
cout << "Do you want repeat? \"y\" or \"n\"\n" << endl;
cin >> answer;
}
}
The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.
For something that you want to run at least once you can also try a do/while statement.
In place of the word "do" you could use the 'while (again!='n');' at that loops lines curly brace (removing that "while again!='n';" check in the process) to have a standard while loop.
while(value==true) { ... }
as opposed to
do { ... } while(value==true);
This would require a properly initialized test variable though.
I included a second while loop in the larger do/while loop for further demonstration.
#include<iostream>
using namespace std;
int main() {
double num1 = 0, num2 = 0;
char op;
char again;
do { // set start point for loop
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)" << endl;
cin >> op;
cout << "Please enter your second number" << endl;
cin >> num2;
if (op == '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!" << endl;
}
cout << "\nRun again? \"y\" or \"n\"" << endl; // prompt user
cin >> again;
// here is a while loop in do/while statement to check for valid input if the user wants
// to go again
while(again!='y' && again!='n'){
cout << "Invalid input. Run again? y or n" << endl;
cin >> again;
}
cout << endl;
} while(again!='n'); // now check if user wants to go again // end of do loop
// the condition for while loop could be like
// while (1); // any non zero being true
// if you want executions until program termination
}
}
Just wrap everything into an endless loop
#include<iostream>
using namespace std;
int main() {
for (;;) {
// your code here
}
}