简体   繁体   中英

I want a function to make a calculation in another function C++

I try to make a function in C++ to assign a value to a variable and keep it, But I want to make with void function . This is the Main function;

int main(){
    //declar variables
    double sales=0.0,commission=0.0,totalCom=0.0,totalSales=0.0,totalEmployee=0.0;
    //call soldEmployee function
    sales = soldEmployee(sales);    
    // if use enter sales negative the programe end
    while(sales > 0){
        //call calc commission
        commisionCalc(sales,commission);
        //call display commission
        displayCom(commission);
        //call display total (commission + sale)
        disTotal(sales,commission,totalEmployee);
        // ask user to put input again
        sales = soldEmployee(sales);
    }
    total(totalSales,commission);

    return 0;
 } //end of main function

And this the function;

double soldEmployee(double &s){//function to get the user input
    cout << "Next Sales: "; cin >> s;   
    return s;   
}

void commisionCalc(double s, double &com){//function to calc commission
    com = s * 0.10;
}

void displayCom(double c){;// function to display commission
    cout <<fixed << setprecision(2) << "Commision= " << c << endl;
}

void disTotal(double s,double com,double &total){// function to get commission + sales
    total = s + com;
    cout << "Salary + Com: " << total << endl;
}

void total(double t, double &total){// function to get the total of all employee commision and store it in total sales
    t += total;
    cout << "Total Salary: " << total << endl;
}

So, in function total I want to make it assign the commission I get into the totalSales, I know that the name of variables seems confusing but, this is because I made some modifies in the program. Can anyone help me explain how to make because I stuck when I made many function. and if you asking that there is a easy way to make i want this way because it's a assignment not work to learn how to make function and get used to it.

I'm not sure I understood the your problem, but if what you need is to have the variable totalSales in the main changed inside the total function so that its modified value would be accessible from the main, you should do the following:

// note below the "double &t" which is now passed by reference.
void total(double &t, double total){
    t += total;
    cout << "Total Salary: " << total << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM