如何将一个函数与另一个函数相乘?以及如何正确使用参数?
我不确定,我真的是C ++的新手,只有大约14周的上课时间。
我尝试过的事情是创建一个新的函数,该函数旨在乘以其他函数,并在参数中输入函数名称。
例如:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
但是我总是遇到错误。请说明如何解决此问题,这对我来说是一个很大的障碍,我似乎无法掌握如何解决此问题或继续做这些事情。为此,请不要对我苛刻。谢谢!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
一个预期结果是我想将用户在函数“ numberOfAdults”中提供的输入与用户为“ mealChoosing”提供的输入相乘
所以我想要numberOfAdults * mealChoosing,但是我希望通过其他功能做到这一点
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
或类似的内容。我无法完成该项目,因为由于某种原因我无法正确地为函数提供参数中所需的适当信息。
答案 0 :(得分:0)
您不能声明参数为函数的函数。而是用一个整数和一个浮点输入来声明进餐:
float mealMath(int a, float b){/*Your code here*/}
然后再将其他两个函数作为参数传递来调用mealMath。
float x = mealMath(numberOfAdults(), mealChoosing());
或者,您无法为mealMath()
使用函数参数,而是从函数内部调用numberOfAdults()
和mealChoosing()
。
重要的是要注意,大多数情况下,您将调用函数并将其输出用作参数,因此,您需要将()
放在函数的标识符之后,而不仅仅是输入唯一的标识符。
答案 1 :(得分:0)
像mealChoosing()
分别从totalAdults
和totalKids
返回numberOfAdults()
和numberOfKids()
(尽管这里不需要)。
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
现在mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());