O.G.
O.G.

Reputation: 15

About reading user input within a function and outputting the result

I've recently been assigned with the task to declare a function, and within that function, read user input 3 times, store that input into 3 variables, and return one value that is calculated by doing operations of sorts to those three variables.

As such, I have had no luck, and need advice.

Here is my code so far:

#include <iostream>
using namespace std;

double calcABCsum(int a, int b, int c);

int main()
{
    int a,
        b,
        c;

    double x;

    calcABCsum();

    cout << "The sum is: " << x;

    return 0;
}

double calcABCsum()
{
    int a;
    int b;
    int c;

    double x;

    cout << "Please enter a: ";
    cin >> a;
    cout << "Please enter b: ";
    cin >> b;
    cout << "Please enter your c: ";
    cin >> c;

    x = a + b + c;

    return x;
}

My code doesn't compile the way I want it to. Basically, I'm looking for a way to read user input in a function and output the result. Thanks!

Upvotes: 1

Views: 160

Answers (1)

bennji_of_the_overflow
bennji_of_the_overflow

Reputation: 1133

There are 2 main problems.

  1. You are declaring the function calcABCSum() at the top of your file as a function which takes 3 variables, but then when you define it below, it takes no parameters.

  2. Once you fix the first issue, you are still just declaring a variable x and not assigning it to any value.

You need to assign your local x variable to the return value of the function you are calling:

double x = calcABCSum(1, 2, 3);

Upvotes: 2

Related Questions