嗨,我正在为一个学校项目工作,而我一生都无法弄清楚如何使totalJobCost函数正常工作。其他函数正常工作,但是我不认为它们将var传递回main以便totalJobCost抢占为totalJobCost输出0。这是我正在使用的代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

void space(double paintarea, double paintcost, double paintneeded, double totalpaint);
void cost(double hrs, double hrcost, double spacetopaint);
void totalJobCost(double allTheirPaintCost, double allTheirWages, double theirTotalJobCost);


const double AREA_FORMULA = 220.00;
const double AREAFORMULA_PAINT = 1.00;
const double AREAFORMULA_HOURS = 8.00;
const double AREAFORMULAHOURS_WAGES = 35.00;

int main()
{
    double areaTP;
    double paintCST = 0;
    double paintNeeded = 0;
    double allPaintCost = 0;
    double hoursNeeded = 0;
    double hoursWages = 0;
    double allWages = 0;
    double allJobCost = 0;

    cout << "Enter the square footage you need to paint, then press enter" << endl;
    cin >> areaTP;

    cout << "Enter the price by gallons of paint you will use, then press enter" << endl;


    cin >> paintCST;
    while (paintCST < 10)
    {
        cout << "Enter the price by gallons of paint you will use, then press enter. cannot be less than 10 :";
        cin >> paintCST;
    }

    space(areaTP, paintCST, paintNeeded, allPaintCost);

    cost(hoursNeeded, hoursWages, areaTP);


    totalJobCost(allPaintCost, hoursWages, allJobCost);


    system("Pause");

    return 0;
}

void space(double paintarea, double paintcost, double paintneeded, double totalpaint)
{

    paintneeded = paintarea / AREA_FORMULA * AREAFORMULA_PAINT;
    totalpaint = paintneeded * paintcost;

    cout << "How many gallons of paint you will need: " << paintneeded << endl;
    cout << "Your total paint cost will be: " << totalpaint << endl;
}

void cost(double hrs, double hrcost, double spacetopaint)
{

    hrs = (spacetopaint / AREA_FORMULA) * AREAFORMULA_HOURS;
    hrcost = hrs * AREAFORMULAHOURS_WAGES;

    cout << "The number of hours for the job will be: " << hrs << endl;
    cout << "The total amount of wages will be: " << hrcost << endl;

}

void totalJobCost(double totalpaint, double hrcost, double theirTotalJobCost)
{
    theirTotalJobCost =  totalpaint + hrcost;

    cout << "The total price of your paint job will be: " << theirTotalJobCost << endl;
}

最佳答案

您需要声明参数(totalpainthrcost)作为引用。

当前,函数space()cost()只是在被调用时制作totalpainthrcost的副本,对其进行更新,然后进行打印。但是,当函数返回时,存储在totalpainthrcost中的值将丢失。

要解决此问题,应按以下方式声明这些功能:

void space(double paintarea, double paintcost, double paintneeded, double& totalpaint)

void cost(double hrs, double& hrcost, double spacetopaint)


现在,当以totalpainthrcost对其进行操作时,以space()cost()传递的任何变量都将被更新。

关于c++ - Paint Job Estimator C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46822118/

10-09 16:46