I'm studying functions in c++ form a book called "jumping to c++" and there are a problem exercise that is create a calculator and I need make the arithmetic operation in separate functions, sound easy and I think I did it 90% good, the program gives me the correct answer but with some random numbers.
the code is:
#include <iostream>
using namespace std;
int a, b;
int sum()
{
return a + b;
}
int subs()
{
return a - b;
}
int div()
{
return a / b;
}
int mult()
{
return a * b;
}
int ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
int main()
{
int opcion;
cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;
if(opcion == 1)
{
cout << ask();
cout << "The result is: " <<sum() <<"\n\n";
} else if (opcion == 2)
{
cout << ask();
cout << "The result is: " << subs() <<"\n\n";
}else if (opcion == 3)
{
cout <<ask();
cout << "The result is: " << div() <<"\n\n";
}else if(opcion == 4)
{
cout << ask();
cout << "The result is: " << mult() <<"\n\n";
}else
{
cout << "Error.\n\n";
}
system("pause");
}
and this is the "error/bug/whatever"
1. Sum
2. Substraction
3. Division
4. Multiplication
Choose one option from above:
4
Give me the first number: 5
Give me the second number: 5
1878005856The result is: 25
Press any key to continue . . .
notice the error before of "The result is:"
appreciate any help, thanks
ask() does not return anything so it should be a void. Also, you do not need to do cout << ask(); since ask() already does the printing inside of it and it is a void (now) so it can't be printed.
Here is the code with the modifications, see comments with **** in front for changes:
#include <iostream>
using namespace std;
int a, b;
int sum() {
return a + b;
}
int subs() {
return a - b;
}
int div() {
return a / b;
}
int mult() {
return a * b;
}
void ask() { // **** Changed to void here
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
int main() {
int opcion;
cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;
if (opcion == 1) {
ask(); // **** Removed cout <<
cout << "The result is: " << sum() << "\n\n";
} else if (opcion == 2) {
ask(); // **** Removed cout <<
cout << "The result is: " << subs() << "\n\n";
} else if (opcion == 3) {
ask(); // **** Removed cout <<
cout << "The result is: " << div() << "\n\n";
} else if (opcion == 4) {
ask(); // **** Removed cout <<
cout << "The result is: " << mult() << "\n\n";
} else {
cout << "Error.\n\n";
}
system("pause");
}
You can try it here
The random number was caused by you doing cout << ask(); even though you had not returned anything.
As aschepler pointed out "make sure you enable and read compiler warnings - there should be one saying that ask() doesn't return anything although declared to return an int."
The problem is your int ask() function.
It must return int value which you are writing to console with cout << ask();
The answer above won't work because you cannot write void to cout.
Since you do not return a value then a random number retruned. My compiler marks that as an error.
Replace type of ask function:
void ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
Then replace cout << ask(); in every if statement with just ask();
Like this:
if (opcion == 1)
{
ask();
cout << "The result is: " << sum() << "\n\n";
}
else if (opcion == 2)
{
ask();
cout << "The result is: " << subs() << "\n\n";
}
else if (opcion == 3) ...
Consider checking if b==0 in case of devision operation. Or your program will crash if u try to devide by zero.
this function is returning a random integer. convert it to void
int ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
new
void ask()
{
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}
Related
I am trying to build a calculator in C++. I'm new to the program and have to do this for a school assignment, so sorry for my ignorance. English is also my second language so excuse me if I don't make much sense.
Let's say I have two integers A and B for which a user has to assign a value to either add, subtract, etc. How would I then be able add a third integer (let's say X) without all three showing up when I run the program? So instead of having to type a value for A, B, AND X, it only asks to type a value for X?
For example 4 + 5 = 9, but the calculator can also square numbers, so how do I get the option of a user just filling in 4 squared = 16, while still keeping the former code that lets me add and subtract two numbers?
Maybe seeing the code would help understand what I mean? Sorry if I'm confusing.
#include <iostream.h>
#include <conio.h>
int main ()
{
cout << "Calculator [v.1.0]" << endl;
cout << "(c) 2021 <Chayenne van der Erf>" << endl << endl;
cout << "Kies een bewerking en druk op Enter:" << endl;
cout << "1. Optellen 2. Aftrekken" << endl;
cout << "3. Vermenigvuldigen 4. Delen" <<endl;
cout << "5. Kwadraat 6. Worteltrekken" <<endl;
cout << "7. Reciproke 8. Logarithme" <<endl;
cout << "0. Exit" << endl << endl;
int Bewerking;
cout << "Bewerking: ";
cin >> Bewerking;
cout << "" << endl;
switch (Bewerking) {
case 1:
cout << "+";
break;
case 2:
cout << "-";
break;
case 3:
cout << "*";
break;
case 4:
cout << "/";
break;
default: "Invalid Number";
}
cout << "" << endl << endl;
double A, B;
cout << "Enter een waarde: ";
cin >> A;
cout << "Enter een waarde: ";
cin >> B;
int antwoord;
if (Bewerking == 1) {antwoord = A + B;}
else if (Bewerking == 2 ) {antwoord = A - B;}
else if (Bewerking == 3) {antwoord = A * B;}
else if (Bewerking == 4) {antwoord = A / B;}
cout << "" << endl;
cout << "= " << antwoord << endl;
getch();
return 0;
}
Make the variables, and the reading, conditional on the operation.
Example outline:
if (operation takes one input)
{
double x;
cin >> x;
Calculate result...
}
else if (operation takes two inputs)
{
double x, y;
cin >> x >> y;
Calculate result...
}
else if (operation takes three inputs)
{
double x, y, z;
cin >> x >> y >> z;
Calculate result...
}
Print result...
I'm working on a project by where I have to create a simple program that works based of the user input. I've gone with a basic calculator but I'm having trouble getting my if/else if statements to work. Basically, if the user types in "Addition", I want the program to say "...I will help you with addition!", and so on for whether the user says "Subtraction", "Division", and "Multiplication".
I'm new to this and so this has already taken me hours upon hours, not looking for you to do it for me but to point out my erorrs and advise so that I can learn from it will be great.
TIA.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
//user inputs what he needs help with/program output
char Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
char inpsum[20];
cin >> inpsum;
char output;
if (inpsum == "Addition")
{
cout << "Great! I'll help you with addition!" << endl;
}
else if (inpsum == "Subtraction")
{
cout << "Great! I'll help you with subtraction!" << endl;
}
else if (inpsum == "Division")
{
cout << "Great! I'll help you with division!" << endl;
}
else if (inpsum == "Multiplication")
{
cout << "Great! I'll help you with multiplication!" << endl;
}
return 0;
REST OF CODE
//addition function
void Add() {
float add1, add2;
cout << "Please enter two values you want added together" << endl;
cin >> add1;
cin >> add2;
cout << "The answer is: " << (add1 + add2) << endl;
}
//subtraction function
void Subt() {
float subt1, subt2;
cout << "Please enter two values you want subtracted" << endl;
cin >> subt1;
cin >> subt2;
cout << "The answer is: " << (subt1 - subt2) << endl;
}
//division function
void Div()
{
float div1, div2;
cout << "Please enter two values you want divided" << endl;
cin >> div1;
cin >> div2;
cout << "The answer is: " << (div1 / div2) << endl;
}
//multiplication function
void Mult() {
float mult1, mult2;
cout << "Please enter two values you want multiplacted" << endl;
cin >> mult1;
cin >> mult2;
cout << "The answer is: " << (mult1 * mult2) << endl;
}
int main()
{
Inpsum(); //user inputs what they want help with
Add();
Subt();
Div();
Mult();
return 0 ;
}
This code is all wrong you need to learn about C++ correctly first, here is the corrected code
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include<string>
using namespace std;
//addition function
float Add(float add1, float add2)
{
return (add1 + add2);
}
//subtraction function
float Subt(float subt1, float subt2) {
return (subt1 - subt2);
}
//division function
float Div(float div1, float div2)
{
return (div1 / div2);
}
//multiplication function
float Mult(float mult1, float mult2)
{
return (mult1 * mult2);
}
void input(float &num1, float &num2)
{
cout << "\nEnter First Number : ";
cin >> num1;
cout << "Enter Second Number : ";
cin >> num2;
}
//user inputs what he needs help with/program output
void Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
float num1;
float num2;
string inpsum;
cin >> inpsum;
if (inpsum == "adding")
{ //if user enters "adding"
cout << "Great!, I will help you with " << (inpsum) << endl;
input(num1, num2);
cout << "\nAnser Is " << Add(num1, num2);
}//then output = "...i will help with adding"
else if (inpsum == "subtraction") //otherwise, if user enters "subtraction"
{
cout << "Great!, I will help you with " << (inpsum) << endl; //then output = "...i will help with subtraction"
input(num1, num2);
cout << "\nAnser Is " << Subt(num1, num2);
}
else if (inpsum == "division") //if user enters "division"
{
cout << "Great!, I will help you with " << (inpsum) << endl; ////then output = "...i will help with division
input(num1, num2);
cout << "\nAnser Is " << Div(num1, num2);
}
else if (inpsum == "multiplication") //if user enters "muliplication"
{
cout << "Great, I will help you with " << (inpsum) << endl; ////then output = "...i will help with multiplication"
input(num1, num2);
cout << "\nAnser Is " << Mult(num1, num2);
}
else
{
cout << "Enter A Correct Mathematical Operation";
}
}
int main()
{
Inpsum(); //user inputs what they want help with
cout<<endl;
system("pause");
return 0;
}
First of all, instead of using char array, use std::string.
Secondly, if-else statements have syntax errors.
Basic structure of if-else statements is like
if(condition)
{
//code
}
else
if(condition)
{
//code
}
More on if-else statements in C++
I'm trying to create a basic console calculator in C++. I'm having a bit of trouble storing a string in a variable from a cin command.
Here is the program for some clarification:
#include <iostream>
using namespace std;
int main()
{
string type_cal;
cout << "Please enter the type of calculation you would like to use: \n";
cout << "1. Addition \n";
cout << "2. Subtraction \n";
cout << "3. Multiplication \n";
cout << "4. Division \n \n";
cin >> type_cal;
if (type_cal = "Addition" or "1")
{
int a;
int b;
int sum;
cout << "Please enter a number to add: \n";
cin >> a;
cout << "Please enter another number: \n";
cin >> b;
sum = a + b;
cout << "The sum of those numbers is: " << sum << endl;
return 0;
}
}
Currently I am in the addition phase since I recently ran into this problem. Quick answers would be appreciated, thank you!
if(type_cal = "Addition" or "1") simply does not make sense.
if(type_cal == "Addition" || type_cal == "1") {
}
Ok I found the problem, or is actually used as || in c++ (thanks aerkenemesis), and = is not the same as == which means equal to (another thanks to Lorehed). Program is working fine now.
For those who are curious, here is the new and revised version of my simple calculator:
#include <iostream>
using namespace std;
float addition();
float subtraction();
float multiplication();
float division();
int main()
{
string type_cal;
cout << "Please enter the type of calculation you would like to use: \n";
cout << "1. Addition " << endl;
cout << "2. Subtraction " << endl;
cout << "3. Multiplication " << endl;
cout << "4. Division" << endl << endl;
cin >> type_cal;
if(type_cal == "Addition")
{
addition();
}
if(type_cal == "Subtraction")
{
subtraction();
}
if(type_cal == "Multiplication")
{
multiplication();
}
if(type_cal == "Division")
{
division();
}
return 0;
}
float addition()
{
float a;
float b;
float sum;
cout << "Please enter a number to add: " << endl;
cin >> a;
cout << "Please enter another number: " << endl;;
cin >> b;
sum = a + b;
cout << "The sum of those numbers is: " << sum << endl;
}
float subtraction()
{
float c;
float d;
float difference;
cout << "Please enter a number to subtract: \n";
cin >> c;
cout << "Please enter another number: \n";
cin >> d;
difference = c - d;
cout << "The difference of those numbers is " << difference << endl;
}
float multiplication()
{
float e;
float f;
float product;
cout << "Please enter a number to multiply: \n";
cin >> e;
cout << "Please enter another number: \n";
cin >> f;
product = e * f;
cout << "The product of those numbers is " << product << endl;
}
float division()
{
float g;
float h;
float quotient;
cout << "Please enter a number to divide: \n";
cin >> g;
cout << "Please enter another number: \n";
cin >> h;
quotient = g / h;
cout << "The quotient of those numbers is " << quotient << endl;
}
Actually i was just trying my hands upon C++ and stopped at this particular problem where instead of program getting closed, it should ask the user whether he/she wants to continue or wants to exit. Now for what i understand, i wrote the do-while code in ending lines but its not working. Please gimme a solution to it. Thanks!!
#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<string>
using namespace std;
class Cal
{
public:
int Add(int a, int b)
{
int res;
res=(a+b);
cout << "Answer is " << a << "+" << b << "=" << res << endl;
}
int Sub(int a,int b)
{
int res;
res=(a-b);
cout << "Answer is " << a << "-" << b << "=" << res << endl;
}
int Mul(int a,int b)
{
int res;
res=(a*b);
cout << "Answer is " << a << "*" << b << "=" << res << endl;
}
int Div(int a,int b)
{
int res;
res=(a/b);
cout << "Answer is " << a << "/" << b << "=" << res << endl;
}
};
int main()
{
int first, second, res, operation;
cout<<"**********************************"<<endl;
cout<<"******* Simple Calculator ********"<<endl;
cout<<"**********************************"<<endl;
cout<<"Select the Operation: "<<endl;
cout<<"1. Addition"<<endl;
cout<<"2. Subtraction"<<endl;
cout<<"3. Multiplication"<<endl;
cout<<"4. Divison"<<endl;
cout<<"Choosen Operation is: ";
cin>>operation;
cout << "Enter the 1st Number: ";
cin>>first;
cout << "Enter the 2nd Number: ";
cin>>second;
switch(operation){
case 1:
Cal a;
a.Add(first,second);
break;
case 2:
Cal b;
b.Sub(first,second);
break;
case 3:
Cal c;
c.Mul(first,second);
break;
case 4:
Cal d;
d.Div(first,second);
break;
default:
cout<< "Please Enter a Operation";
break;
}
char ans;
do
{
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N' :";
cin >> ans;
}
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}
The do while loop does not enclose the body to be repeated, i.e. the calculator part.
The condition in do while does not look correct.
I would try this.
int main() {
char ans = 'N';
do {
// calculator stuff, better to be in a separate function
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N' :";
cin >> ans;
} while ((ans == 'Y') || (ans == 'y'));
}
A fine gentleman told me that goto statements were bad, but I don't see how I can not use it here:
int main()
{
using namespace std;
int x;
int y;
int z;
int a;
int b;
Calc: //How can i get back here, without using goto?
{
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
if (b == 1) {
goto Calc;
}
cout << "Happy trails!" << endl;
return 0;
}
It is a calculator, as you can see. Also, if you want, can you suggest a better way (If it exists) to let the user choose the operation (+ - * /). Header files are under control.
I apologize for a lot of cout statements.
Here is a cleaned-up and properly formatted version using a do/while loop for structure:
using namespace std;
int main()
{
int x, y, z, a, b;
do {
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
else if (a == 2) {
z = sub(x, y);
}
else if (a == 3) {
z = mul(x, y);
}
else if (a == 4) {
z = dis(x, y);
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
} while (b != 0);
cout << "Happy trails!" << endl;
return 0;
}
Erm , use a proper looping construct, while, for etc.
the "more generally accepted" approach in this case would be a do {...} while(b==1); but the compiled results would likely be identical.
goto makes it difficult to track where execution is coming from, and where it's going.
goto encourages spagetti-code, unless you restrict heavily where it is used (e.g. you could argue that you only use it for cleanup blocks, but such an argument makes no sense in the presence of RAII).
you are using a goto to simulate a loop. Why are you not writing a loop instead?
it's obscure and thus, makes your code less available to other people.
goto makes it more difficult to track objects lifetimes.
Short answer to actual question: No, you should not use goto in this code. There is no need for it.
The use of goto should be "when it makes the code clearer or safer". The typical example of "makes the code clearer" is when there several layers of nested loops, and some particular situation requires leaving all the nesting levels, and adding a "do we want to exit the loop" makes the code more complicated. An example of "making it safer" is if a function holds a lock, opens a file or something similar, and needs to return early - but you also need to close the file or release the lock, using "goto exit_now;" is safer than trying to remember what locks, files, etc are held and then doing return;.
This:
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
is a classic case of you should use 'switch':
switch(a)
{
case 1:
z = add(x, y);
break;
case 2:
z = sub(x, y);
break;
....
}
Makes the code clearer - there is also no confusion about whether a changes value and maybe another if statement becomes viable.
You can easily avoid 'goto' in your code. Just divide it into functions:
using namespace std;
void question () {
cout << "To begin, type a number" << endl;
cin >> x;
// put rest of the code here
}
int main () {
int ask = 1;
while ( ask == 1 ) {
question();
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> ask;
}
return 0;
}
Edit: as noted in the comments, using do-while would be actually an better option.
goto isn't automatically bad. Unreadable code is bad. Whenever you find yourself in need of some obscure programming construct like 'goto', that usually means that your code is either poorly written, or that your program design is flawed.
The solution is almost always more functions. For example:
bool run_program();
int prompt_user_begin();
int prompt_user_again();
int prompt_operation_type();
bool prompt_continue();
int main()
{
while(run_program())
{}
cout << "Happy trails!" << endl;
return 0;
}
bool run_program()
{
int first;
int second;
int operation_type;
int result;
first = prompt_user_begin();
cout << "Excellent!" << endl;
second = prompt_user_again();
cout << "Excellent!" << endl;
operation_type = prompt_operation_type();
switch(operation_type)
{
case 1: result = add(first, second); break;
case 2: result = sub(first, second); break;
case 3: result = mul(first, second); break;
case 4: result = div(first, second); break;
}
cout << "The answer to your math question is ";
cout << result << endl;
return prompt_continue();
}
int prompt_user_begin ()
{
int x;
cout << "To begin, type a number" << endl;
cin >> x;
return x;
}
int prompt_user_again ()
{
int x;
cout << "Now you need to type the second number" << endl;
cin >> x;
return x;
}
int prompt_operation_type ()
{
int x;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> x;
return x;
}
bool prompt_continue ()
{
int x;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> x;
return x==1;
}