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
Related
I've written a program for my C++ class and I ran into a little problem which I'm not quite sure how to solve. Some of you may be familiar with this textbook exercise as I've seen questions asked about it on the site before, but I was unable to find any simple fix.
I have to create a class which is used to store information about a pizza. I've got the program written and functional, but I need the class call to loop through a series of iterations based on the user's input. I know that this can be achieved using vectors, something we haven't hit yet in the semester, but will get to soon enough I'm sure. Is there a way to do this without vectors?
Here's the class.
class Pizza
{
private:
int type;
int size;
int numCheeseTopping;
int numPepperoniTopping;
bool cheeseTopping;
bool pepperoniTopping;
public:
Pizza();
int getType();
int getSize();
bool getCheese();
bool getPepperoni();
void setType(int t);
void setSize(int s);
void setCheese(bool choice, int temp);
void setPepperoni(bool choice, int temp);
void outputDescription();
double computePrice();
void outputPrice();
};
And the constructor.
Pizza::Pizza()
{
// Set initial class values
type = DEEPDISH;
size = SMALL;
cheeseTopping = false;
numCheeseTopping = 0;
pepperoniTopping = false;
numPepperoniTopping = 0;
}
Main is only two functions.
// Main function
int main()
{
// Call global functions
welcomeMsg();
buildPizza();
return 0;
}
I have a feeling that my problem lies in the buildPizza function, as it calls other functions as well as creating the objects. Here it is...
void buildPizza()
{
char pType, pSize, tempCheese, tempPepperoni;
int type = 0, size = 0, numCheeseTopping = 0, numPepperoniTopping = 0;
// Ask user what size pizza they would like.
cout << "What size pizza would you like?" << endl;
cout << "\tS: Small" << endl;
cout << "\tM: Medium" << endl;
cout << "\tL: Large" << endl;
cout << "Size: ";
cin >> pSize;
// Determine which size the user input and convert the
// result.
switch (pSize)
{
case 'S':
case 's':
size = SMALL;
break;
case 'M':
case 'm':
size = MEDIUM;
break;
case 'L':
case 'l':
size = LARGE;
break;
}
// Ask the user which type of pizza they would like.
cout << endl << "What type pizza would you like?" << endl;
cout << "\tD: Deepdish" << endl;
cout << "\tH: Hand-Tossed" << endl;
cout << "\tP: Pan" << endl;
cout << "Type: ";
cin >> pType;
// Determine which type the user input and convert the
// result.
switch (pType)
{
case 'D':
case 'd':
type = DEEPDISH;
break;
case 'H':
case 'h':
type = HANDTOSSED;
break;
case 'P':
case 'p':
type = PAN;
break;
}
// Call Pizza Class.
Pizza myPizza;
// Call Pizza Class functions.
myPizza.setSize(size);
myPizza.setType(type);
// Ask user whether they want cheese or not.
cout << endl << "Would you like cheese (y/n)? ";
cin >> tempCheese;
// If so call setCheese.
if (tempCheese == 'Y' || tempCheese == 'y')
{
cout << "How many cheese toppings would you like? ";
cin >> numCheeseTopping;
myPizza.setCheese(true, numCheeseTopping);
}
// Ask user whether they want pepperoni or not.
cout << endl << "Would you like pepperoni (y/n)? ";
cin >> tempPepperoni;
// If so call setPepperoni.
if (tempPepperoni == 'Y' || tempPepperoni == 'y')
{
cout << "How many pepperoni toppings would you like? ";
cin >> numPepperoniTopping;
myPizza.setPepperoni(true, numPepperoniTopping);
}
// Call outputDescription to give user an overview
// of their order.
cout << endl << endl;
myPizza.outputDescription();
cout << endl;
// Compute the cost of the pizza and display it.
myPizza.outputPrice();
}
Basically, I'd like the program to ask the user how many pizzas they would like to evaluate, create that many class iterations, then cycle through 'building' or 'ordering' each pizza, then display a total and return 0.
As I look at the code now I can take the last two function calls out of buildPizza and move the calls into main, but this will not solve my problem. Only an oversight I literally just noticed within the program.
Is there an easy way to create, say, 200 new objects all at once at runtime. Each one with a different name? Should I just pick a number to evaluate and force the user to enter information for that many objects? Right now, the program evaluates one pizza and quits.
I'd like something like this to happen:
User asks program to create a 5 pizza order.
Program creates 5 pizza objects.
Program iterates through each object getting and setting information for each one.
Program displays some stuff and returns 0.
Is this possible with my code, or do I need to consider a rewrite? Any guidance the community can give me will be immensely helpful.
Thanks.
Kyle
Since you cnanot use arrays or vectors, a simple for would suffice.
auto nrPizzas = getNumberOfPizzasFromUserInput();
for(int i = 0; i < nrPizzas; i++) {
auto pizza = Pizza{};
// do your stuff here.
output to the screen here();
}
You can prompt for the number of pizzas user want and then create a dynamic array of that much pizzas and then iterate through their build function or else you can make a linked-list with struct type of pizza and then rewrite the main logic. Second approach is advised if you do not want to prompt that how many pizza's the user wants to order.
I am a noob to C++, and as a part of homework I had to create a simple calculator with four functions within C++. I have done this and it works, however, I am now trying to loop it so that a user can have infinite attempts at using it, however, I am having struggles. Basically, when I run my program and tell the program which operation I'd like to use, it tells me that my variable "sum" is not being initialized. Im not quite sure what this is, or how to fix it. Any ideas? Here is my code -
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
while (true)
{
int num1, num2, r;
double sum;
cout << "Enter a number\n";
cin >> num1;
cout << "Enter another number\n";
cin >> num2;
cout << "Please enter an operator (+ , * , /, - or End)\n";
cin >> r;
if (r == 'End') break;
if (r == '+') sum = num1 + num2;
if (r == '-') sum = num1 - num2;
if (r == '*') sum = num1 * num2;
if (r == '/') sum = num1 / num2;
cout << r;
cout << "The answer is \n" << sum << endl;
system("pause");
return 0;
}
}
If the user enters 'a' as operator for example (something else than the valid choices), sum is never assigned a value, but sum is printed.
As others have said, the variable sum remains uninitialized if the user enters an invalid choice for r. Just set double sum=0; and you're good to go.
In addition, 'End' is not a char, so you can't compare it to r. You'll have to use some other option for ending.
The compiler says that you are trying to use an unintialized variable, sum.
If you think you initialize it, think again: You only assign a value if r is +, -, * or /. But what if r is a? 'End' is not a character, and thus invalid
Then sum is never initialized/has a value, and so the compiler complains.
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;
}
I have to use a enumerations to represent the difficulty levels. Here is the code.
// Menu Chooser
// Demonstrates the switch statement
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
enum userChoice {Easy, Normal, Hard};
userChoice choice;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
break;
case 2:
cout << "You picked Normal.\n";
break;
case 3:
cout << "You picked Hard.\n";
break;
default:
cout << "You made an illegal choice.\n";
}
return 0;
}
and the error message:
error C2678: binary '>>' : no operator found which takes a left-hand
operand of type 'std::istream' (or there is no acceptable conversion)
There is no default implementation of the >> operator for taking an input and mapping it to an enum. You will need to take in an int as an input and then map it to the enum. Alternatively, you could write an overload for the >> operator that maps the input to your enum.
Of course, looking at your code, you don't seem to be using the defined enum for anything. Perhaps you could remove it and use an int instead?
You need to place your enum values into your cases:
switch (choice)
{
case Easy:
cout << "You picked Easy.\n";
break;
case Normal:
cout << "You picked Normal.\n";
break;
case Hard:
cout << "You picked Hard.\n";
break;
default:
cout << "You made an illegal choice.\n";
}
To convert from text to enum type, I suggest you use a table (your instructor probably hasn't covered the topic of std::map which would be the preferred method).
struct Enum_Entry
{
UserChoice value;
const char * text;
};
static const Enum_Entry lookup_table[] =
{
{Easy, "easy"},
{Normal, "normal"},
{Hard, "hard"},
};
static const unsigned int items_in_table =
sizeof(lookup_table) / sizeof(lookup_table[0]);
std::string selection_text;
// Input enum as text
std::cin >> selection_text;
// Convert to lower case to make comparison easier
std::transform(selection_text.begin(), // Start of range
selection_text.end(), // End of range
selection.begin(), // Destination for transformation.
std::tolower); // Transformation function.
// Lookup the text into the table and retrieve the enum value.
UserChoice choice = Easy;
for (unsigned int i = 0; i < items_in_table; ++i)
{
if (selection_text == lookup_table[i].text)
{
choice = lookup_table[i].value;
break;
}
}
Another method is to use an if-else-if ladder:
choice = easy;
if (selection_text == "easy")
{
choice = Easy;
}
else if (selection_text == "hard")
{
choice = Hard;
}
else if (selection_text == "normal")
{
choice = Normal;
}
else
{
choice = Easy;
}
When reading user input, it is not safe to expect they will enter a correct value. However, this seems extreme for your assignment.
My first thought is to just read in an int, then cast it to the enum.
int input;
cin >> input;
userChoice choice = (userChoice)input;
This should work, however I haven't tested it.
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');
}