I got trouble making functions in c++
Oct 8, 2018 at 9:04am UTC
Help from my code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// Calculator.cpp - This program performs arithmetic, ( +. -, *. / ) on two numbers.
// Input: Interactive
// Output: Result of arithmetic operation
#include <iostream>
#include <string>
using namespace std;
// Write performOperation() function declaration here
int main()
{
double numberOne, numberTwo;
string operation;
double result;
cout << "Enter the first number: " ;
cin >> numberOne;
cout << "Enter the second number: " ;
cin >> numberTwo;
cout << "Enter an operator (+.-.*,/): " ;
cin >> operation;
// Call performOperation method here
cout << numberOne;
cout << " " << operation << " " ;
cout << numberTwo;
cout << " = " ;
cout << result << endl;
return 0;
} // End of main() function
// Write performOperation function here
Oct 8, 2018 at 9:21am UTC
You can call it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
#include <string>
using namespace std;
double performOperation(string operation, double numberOne, double numberTwo)
{
// you need to provide the implementation here.
return 0.0;
}
int main()
{
double numberOne, numberTwo;
string operation;
double result;
cout << "Enter the first number: " ;
cin >> numberOne;
cout << "Enter the second number: " ;
cin >> numberTwo;
cout << "Enter an operator (+.-.*,/): " ;
cin >> operation;
result = performOperation(operation, numberOne, numberTwo);
cout << numberOne;
cout << " " << operation << " " ;
cout << numberTwo;
cout << " = " ;
cout << result << endl;
return 0;
}
Oct 8, 2018 at 3:10pm UTC
Why use a
std::string when your operator input is a single character?
Passing
Plain Old Data variables "by value" as parameters by copying them is a trivial expense, but passing them as pointers or references is a better technique to learn for later when dealing with classes and structs that can be quite a chore to copy.
If you pass by pointer or reference then making the parameters
const is recommended if you don't want to change the parameters in the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
double performOperation(const char &, const double &, const double &);
int main()
{
std::cout << "Enter the first number: " ;
double numberOne;
std::cin >> numberOne;
std::cout << "Enter the second number: " ;
double numberTwo;
std::cin >> numberTwo;
std::cout << "Enter an operator (+, -, *, /): " ;
char operation;
std::cin >> operation;
double result = (operation, numberOne, numberTwo);
std::cout << numberOne << " " << operation << " " << numberTwo << " = " << result << '\n' ;
return 0;
}
double performOperation(const char & operation, const double & numberOne, const double & numberTwo)
{
// do the math op magic here.
return 0.0;
}
Topic archived. No new replies allowed.