我理解如何从函数中传递变量,但我一直坚持将多个函数组合在一起?我想将函数中存储的所有double值添加到一个名为" totalBillAmount"的函数中。 (navyCreditBill + wfStudentBill + ....等)。此外,有没有办法结合功能,即使他们都有不同的双重值? (即将所有票据合并成一个名为票据的函数)
//this is my main file
Budget budget;
budget.introText();
double inputNavyCreditCardBill = budget.navyCreditBill();
double inputWellsStudentLoanBill = budget.wfStudentBill();
double inputSprintPhoneBill = budget.sprintBill();
double carBill = budget.carBill();
double capitalOneCreditCard = budget.capitalCredit();
double fedStudentLoan = budget.fedCreditBill();
double navyPersonalLoan = budget.navyPersonalLoan();
double totalMoneyOnHand = budget.totalMoneyOnHand();
double totalBillAmount =
double moneyRemaining = totalMoneyOnHand - totalBillAmount;
std::cout << std::endl << "Money Remaining: $" << moneyRemaining << std::endl;
double extraMoneyTowardsDebt = moneyRemaining * .7;
std::cout << std::endl << "Extra Money For Debt: $" << extraMoneyTowardsDebt << std::endl;
double moneyFromCreditForGirlFriend = moneyRemaining * .3;
std::cout << "Extra Money From Credit For Girlfriend!: $" << moneyFromCreditForGirlFriend << std::endl;
double extraMoneyForMe = moneyRemaining * .3;
std::cout << "MA MONEY BITCH: $" << extraMoneyForMe << std::endl;
return 0;
}
答案 0 :(得分:0)
假设您有以下功能:
void func1(int bar1) { ... }
void func2(int bar2) { ... }
void func3(int bar3) { ... }
如果你想将所有这些函数组合在一个新的更大的函数中,你需要做的就是通过大函数的参数列表传递每个小函数所需的参数:
void bigFunc(int bar1, int bar2, int bar3) {
...
func1(bar1);
func2(bar2);
func3(bar3);
}
现在,在您的情况下,您还有返回值,这会使事情变得更复杂一些。根据您对这些操作的要求,您可以在big函数中进行计算,然后返回单个结果,或者使用数组,结构或更复杂的容器来存储单独的结果。
因为在你的情况下你只想返回一个结果,这很容易。您可以在下面看到包含大量函数的示例(double sum(double, double, double)
,double pow(double, double)
和double sub(double, double)
)。您应该能够根据您的场景进行调整:
// Use the arguments list of bigFunc to pass down the arguments that each of the smaller function requires
void bigFunc(double arg1, double arg2, double arg3) {
// Use temporary variables to store the return value of each smaller function
double s = sum(arg1, arg2, arg3);
double p = pow(arg1, arg3);
double sb = sub(arg1, arg2);
// Do whatever you want we the results and return it
return s + p - sb;
}