Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am a programming beginner and I am doing one exercise that I found on the internet:
Make a calculator that takes 3 inputs and adds, subtracts, multiplies or divides two numbers.
The first and third input being ints. The second being a char.
Use a switch statement to figure out what operation to do depending on the user input.
Use at least one function.
Have the program ask again if the input is invalid.
Make the program loop after completion, allowing multiple uses before it exits completely.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int number1 , number2;
char operator_;
cout << "enter first number:" << endl;
cin >> number1;
cout << "enter operator:";
cin >> operator_;
cout << "enter second number:" << endl;
cin >> number2;
switch (operator_)
{
case '+':
cout << " the sum is " << number1 + number2;
break;
case '-':
cout << "the difference is " <<number1 - number2;
break;
case '*':
cout << "the product is " << number1 * number2;
break;
case '/':
cout << "the quotient is " << number1 / number2;
break;
default:
cout << "Invalid Operation";
}
return 0;
}
How can I accomplish task 3 and 4? I studied while loops but I don't know how that is gonna help with my program.thanks
Just add an infinite loop outside all your code in the main function, and at the end ask the user if he/she wants to continue. If not then break out of the loop.
You could do both in one go if you like.
First rename your main function, call it something like do_calculation.
Now write a new main function. This one will contain a loop to ask if the users wants to try again, and it will call the do_calculation function you've just created. Something like this
int main()
{
char try_again;
do
{
do_calculation();
cout << "Do you want to try again (answer Y or N) ";
cin >> try_again;
}
while (try_again == 'y' || try_again == 'Y');
}
Related
This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm writing a code which is kind of like a fortune teller but I'm having some trouble with my switch statements. When executed the code prints out the same message and doesn't pick a random case like its supposed to! can someone please help me! thank you!
heres my code
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void printGreeting(); // function prototype
int main()
{
int choice;
printGreeting();
cout << "Would you like to see your fortune?" << endl;
cout << "Press 1 to see your fortune or 2 if you don't!" << endl;
cin >> choice;
if (choice == 1)
{
cout << "Great! Your fortune is: ";
// Function to generate random number
void rand1();
srand(time(NULL));
int MAX_NUM;
MAX_NUM = 5;
int random = rand() % MAX_NUM;
cout << random << endl;
int selection;
selection = 5;
switch (selection)
{
case 1:
cout << "Change can hurt, but it leads a path to something better!";
break;
case 2:
cout << "If you have something good in your life don't let it go!";
break;
case 3:
cout << "You're in for a treat today.";
break;
case 4:
cout << "Land is always on the mind of a flying bird";
break;
case 5:
cout << "A dream you have will come true";
break;
}
return 0;
}
else if (choice == 2)
{
cout << "Okay goodbye!" << endl;
}
}
// Prints greeting message
void printGreeting() // function header
{
cout << "Hello! Welcome to your fortune teller!" << endl; // function body
}
Because selection = 5;
You want to choose selection with a random value between 1 - 5, right?
You switch by selection variable, which is explicitly set to 5 right before the switch itself. Consider switching by random variable.
This is my first time on this web site. I have been having a problem but I haven`t been able to figure it out. I have been trying to implement a predefined function into my code but I am not sure how to do so. In my Task I was given an open brief asking me simply to design a password protected calculator. I designed the calculator and handed it in to my teacher. He then asked me to add a predefined function. Now I am not sure how to do this or even how I would start. Could any one give me some example of a predefined function similar to my code.
#include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
int correct_password = 1998;
int password = 0;
int counter = 0;
int attempt = 0;
while (attempt <= 3) {
cout << "Enter your password: ";
cin >> password;
attempt = attempt + 1;
if (password != correct_password) {
cout << "Incorrect password combination. Please try again." << "\n" << endl;
} else {
break;
}
}
if (attempt >= 3) {
return 0;
}
cout << "Access granted." << endl;
//Asks you to enter an operator to use in your calculation
cout << "Enter operator either + or - or * or /: ";
cin >> op;
//Asks you to enter 2 numbers
cout << "Enter two operands: ";
cin >> num1 >> num2;
//Searches for which operator you have selected and Either *-+/ the number depending on choice
switch (op) {
case '+':
cout << num1 + num2;
break;
case '-':
cout << num1 - num2;
break;
case '*':
cout << num1 * num2;
break;
case '/':
cout << num1 / num2;
break;
//If entered operator is incorrect closes down the program
default:
cout << "Error! operator is not correct";
break;
}
return 0;
}
Sorry for the trouble. I am not quite sure if I am going about asking this the right way. so I will apologies before hand if I am not specific enough or if I am doing ti wrong :).
(edit:: added some explanation)
I can't know what exactly your teacher wanted, but it might be something like this:
void foo(float a, float b){
return a+4*b;
}
Allowing your calculator to use a function like that would work in the following way:
... //Your previous code here
switch(op){
... // Your other switches here
case 'f':
cout<<foo(num1,num2)<<endl;
break;
}
... //Your following code here
The 'f' here stands for the command "EXECUTE PREDEFINED FUNCTION" instead of '+' for "ADD" or '-' for "SUBTRACT".
That way you could have a predefined function and execute that on your numbers.
In this case we would see the entred number num1 be added to four times the entered number num2
I hope it helped :)
these function are in library #include<math.h> You need to use this header file in order to use those function in your code .
It includes predefined functions such as
sqrt(number);
This function is used to find square root of the argument passed to this function.
pow(number);
This is used to find the power of the given number.
trunc(number);
This function truncates the decimal value from floating point value and returns integer value
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have only really been coding for a few days, though I've reading the textbook for my Intro to C++ class for two weeks. I'm having an issue with an assignment, and I feel like I'm missing something super simple, but I can't understand what I've done wrong.
The exercise calls for you to 'write a program that reads numbers from cin, and then sums them, stopping when 0 has been entered.'
The professor told us we could write it with a for loop, a while loop, or a do-while loop. I am trying to write it with a for loop.
The program compiles successfully, it allows me to enter multiple values, and it sums it correctly. It also stops on no successfully. The only thing that's wrong with it is when I enter 0, it does not stop the program. I have tried using different commands inside the for loop, such as goto, and trying to direct it to go to break; when the value entered is zero, but my knowledge is shoddy, to say the least. I've read the textbook but I don't have enough experience yet, and I don't remember everything, and I can't figure out what I'm doing wrong.
This is what the program looks like:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char indicator{ 'n' };
double value{};
double sum{};
for (;;)
{
cout << endl
<< "Enter a value here: ";
cin >> value;
sum += value;
cout << endl
<< "Do you want to enter another value (enter y or n)? ";
cin >> indicator;
if (('n' == indicator) || ('N' == indicator))
break;
}
cout << endl
<< "The sum of the values you entered is " << sum << "."
<< endl;
return 0;
}
Please point out my stupid mistake, I'd be grateful to learn. Thank you!
There is no sense to ask the user each time whether he wants to continue.
So I would write the loop the following way
cout << "Enter a sequence of real numbers (0 - exit): ";
for (;;)
{
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
Also as the variable value is used only in the body of the loop it should be declared there. So the loop can look like
cout << "Enter a sequence of real numbers (0 - exit): ";
for (;;)
{
double value;
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
An alternative for this for loop is while loop of the following form
cout << "Enter a sequence of real numbers (0 - exit): ";
while ( true )
{
double value;
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
Just compare value to zero after it is inputted:
for (;;)
{
cout << endl
<< "Enter a value here; enter 0 to stop: ";
cin >> value;
if(value==0.0) break;
sum += value;
}
I would like to make a few suggestions to you which you may find helpful.
To begin, any of the loops you mentioned (for, while, do while) may be used in solving this problem. But I believe that the do while lends itself best to this particular problem.
The use of a for is especially bad for this exercise as for loops are typically employed while performing iterations over a set of values or some sort of finite counting. Being asked to perform an action an indefinite number of times is better suited for a while or do while.
Just look at your for declaration:
for(;;)
{
// ...
}
What benefit does using for have in this situation if you make use of none of it's functionality.
Second, the use of double is for your value and sum is not recommended either. This is because of something called floating-point precision. You can not reliably compare a double value using ==. See: What is the most effective way for float and double comparison?
Instead, unless specified by the problem statement, I would opt to use an integer value type. Either int or unsigned int.
Third, you are not correctly initializing your variables. Instead, it should be done as:
int value = 0;
int sum = 0;
Improper variable initialization can lead to countless bugs and is a very common source of problems.
Finally, I would recommend against the use of using namespace. This is used commonly by beginner developers who then are taught better practices and then have to unlearn the behavior. See: Why is "using namespace std" considered bad practice?
Taking this advice into consideration would lead to a solution such as:
#include <iostream>
int main(int argc, char** argv)
{
int sum = 0;
int value = 0;
do
{
sum += value;
std::cout << "Please enter a value: ";
std::cin >> value;
} while(value != 0);
std::cout << "The sum of all values entered is: " << sum;
return 0;
}
ITNOA
You can just change
cout << endl
<< "Do you want to enter another value (enter y or n)? ";
cin >> indicator;
if (('n' == indicator) || ('N' == indicator))
break;
with
cout << endl
<< "Do you want to enter another value (enter 0 for exit or not zero to continue)? ";
int indicator = -1;
cin >> indicator;
if (indicator == 0)
break;
If you do not want to ask user to continue enter new value in every time #Govind Parmar and #Vlad from Moscow write cleaner code than you write.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i cant figure out where to put all the loop parts for a simple y/n (repeat/exit) loop.i tried to find answers, but none are clear enough for my particular case.
P.S. iam a beginner at coding, so please dont make it too complicated unless necessary
this is my code so far
#include <stdio.h>
#include <iostream>
using namespace std;
// input function
void Input (float &x, float &y);
float a=1.0, b=1.0, result;
char operation;
char yesNO;
int main ()
{
do {
cout << "Programma wat optelt, aftrekt, vermedigvuldigd en deelt. \n\n";
cout << "Geef een opdracht (eg. 1 + 2): \n";
cin >> a >> operation >> b;
Input (a,b);
cout << "Het antwoord is: " << result << endl;
system ("pause");
return 0;
}
while (yesNO == 'y');
void Input (float &x, float &y)
{
a = x;
b = y;
switch (operation)
{
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout << "foutieve invoer: \n";
cin >> a >> operation >> b;
Input (a, b);
}
}
}
I'll ignore some of the things wrong with your program and answer the question directly.
Two things:
You are never asking the user if they want to continue
You are aborting your loop by returing out of main()
So replace these 2 lines:
system ("pause");
return 0;
with a query that asks the user if they want to continue, and populate the variable yesNO with their answer.
It stops because of the return statement in "int main". I would suggest using "void main ()" instead of "int main ()". But if you want to use "int main ()", shift the "return 0" below the while statement. You also need to ask the user if he or she wants to continue. Try this: (Ignore the bad spacing)
int main () {
do {
cout << "Programma wat optelt, aftrekt, vermedigvuldigd en deelt. \n\n";
cout << "Geef een opdracht (eg. 1 + 2): \n";
cin >> a >> operation >> b;
Input (a,b);
cout << "Het antwoord is: " << result << endl;
cout << "Press y to continue: ";
cin >> yesNo;
} while (yesNO == 'y');
return 0;
}