0

We were tasked on using non void functions to create a mini calculator where a user can input an arithmetic operation of their own choice, however I am getting a weird answer on my output here is my code so far

#include <iomanip>
#include <iostream>

using namespace std;

double ArithmeticOperation(float x, float y, string opt, double result)
{
    if (opt == "+") {
        result = x + y;
    } else if (opt == "-") {
        result = x - y;
    } else if (opt == "*") {
        result = x * y;
    } else if (opt == "/") {
        result = x / y;
    }
    return result;
}

int main()
{
    string opt;
    float x, y;
    double result;

    cout << "Enter an Arithmetic Operator (+,-,*,/): ";
    cin >> opt;

    cout << "Input first number: ";
    cin >> x;

    cout << "Input second number: ";
    cin >> y;

    ArithmeticOperation(x, y, opt, result);
    cout << "The answer is: " << result;

    return 0;
}

I inputted 1+2 on my user input program and got 4.68151e-310 as the answer this also occurs wheter its subtraction, multiplication and division and whatever number I input as x and y.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
Mopy
  • 1
  • 1
    `result` is uninitialized and you're passing it by value so undefined behavior as it has indeterminate value. – Jason Nov 22 '22 at 03:06
  • 1
    After initializing, you need to pass the `result` by reference. – Rohan Bari Nov 22 '22 at 03:08
  • Despite what others might say, you do not need to pass `result` by reference. In fact, I suspect you are intended to not pass `result` at all to your function. Ignoring the value returned by "non void functions" is not significantly different than using void-returning functions. – JaMiT Nov 22 '22 at 03:42
  • Did you try to inspect the value of `opt`? (E.g. `cout << "opt is: $" << opt << "$";`?) Maybe it contains some superfluous whitespace? Note that your function doesn't fill in `result` when `opt` isn't **exactly** equal to one of the 4 given strings. You might want to issue and error in that case. – JohanC Nov 22 '22 at 07:00

0 Answers0