'I am getting a weird output on my cout, it puts the answer first then puts a weird output where I call it. What do I do?

#include <iostream>
using namespace std;

//MainFunctions
int computeDiscount(int);
int mainProgram();

int main()
{
    mainProgram();
}

int computeDiscount(int total)
{
    if (total >= 10 && total <= 19)
    {
        total = (total-(total * .2));
        cout << total;
    }
}

int mainProgram()
{
    int t;
    cout << "What is the total amount for today? " << endl << ">>>";
    cin >> t;

    cout << "The total is: " << computeDiscount(t);
}

Output: 
What is the total amount for today?

10

7The total is: 5007456

What do I do? I want seven to go where the "5007456" is appearing

If I put the function outside of the cout it works... Not sure

I want to call the function in the cout

c++


Solution 1:[1]

int computeDiscount(int total)
{
    if (total >= 10 && total <= 19)
    {
        total = (total-(total * .2));
        cout << total;
    }
}
In this method you are not returning any integer which is suppose to be there and in main function you are trying to print the output which will give you garbage value.

Solution 2:[2]

#include <iostream>
using namespace std;

//MainFunctions
int computeDiscount(int);
int mainProgram();

int main()
{
    mainProgram();
}

void computeDiscount(int *total)
{
    if (*total >= 10 && *total <= 19)
    {
        *total = (*total-(*total * .2));
    }
}

int mainProgram()
{
    int t;
    cout << "What is the total amount for today? " << endl << ">>>";
    cin >> t;
    computeDiscount(&t);
    cout << "The total is: " << t;
    return 0;
}

Or you can pass reference to the function

Solution 3:[3]

in place of cout << total;
is return total;

int computeDiscount(int total)
{
    if (total >= 10 && total <= 19)
    {
        total = (total-(total * .2));
        return total;
    }
}

and do properly ie. take the most C/C++ advantageous feature

 int computeDiscount(int total)
    {
        if (total >= 10 && total <= 19)
            return total -= total / 5 ;
         return   
    }

Solution 4:[4]

Use pass by reference in function computeDiscount(int&)

int computeDiscount(int&);

int computeDiscount(int& total)
{
    if (total >= 10 && total <= 19)
    {
        total = (total-(total * .2));
        cout << total;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajeev
Solution 2 Rajeev
Solution 3
Solution 4 Rajeev