Function return not returning a value to main

若如初见. 提交于 2021-02-05 11:30:22

问题


So, this is my first assignment fiddling with functions in C++ - which I thought I understood being as they're rather similar to methods with C#. But, although my main calls my function fine, and the function runs and returns to the main - It doesn't send back the variable information that it called when it returns. I'm not exactly sure what I've done wrong - it appears to be set up appropriately (IE - Like the sample code in my book for a return) Here's the main code...

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main()

{

    double retrieveSales=0, sales1=0, sales2=0, sales3=0, sales4=0;
    string division, division2, division3, division4;
    double getSales(string);

    cout<<"Enter division.\n";
    cin>>division;

    getSales(division);
    retrieveSales=sales1;

    cout<<"Enter second division.\n";
    cin>>division2;

    getSales(division2);
    retrieveSales=sales2;
    cout<<"Print Sales"<<sales2;

    cout<<"Enter third division.\n";
    cin>>division3;

    getSales(division3);
    retrieveSales=sales3;
    cout<<"Print Sales"<<sales3;

    cout<<"Enter fourth division.\n";
    cin>>division4;

    getSales(division4);
    retrieveSales=sales4;
    cout<<"Print Sales"<<sales4;

    system("pause");
    return 0;
    }

And here's the code for the function that it calls

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

double getSales(string division)
{
    double retrieveSales;

    cout<<"What are the sales for "<<division<<endl;
    cin>>retrieveSales;
    while(retrieveSales<0.0)
    {
        cout<<"Please enter a valid sales amount no less than $0.00.\n";
        cin>>retrieveSales;
    }
    system("pause");
    return retrieveSales;
}

How do I get my function to return the value of retrieveSales to retrieveSales in the main?


回答1:


In this line:

getSales(division);

You are discarding the return value, you need to assign it to a variable:

sales1 = getSales(division);


来源:https://stackoverflow.com/questions/15188045/function-return-not-returning-a-value-to-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!