C++ 函数的声明跟定义
遇到一道题,函数中套函数,这种题应该怎么做。毫无头绪。懵逼当中。谢谢大神们帮忙解答。题目要求:
#include <iostream>
using namespace std;
//函数声明
int main ()
{
int number of items,total calories;
number of items= getInput();
total calories= calcCalories(number of items);
displayOutput(number of items, total calories);
return 0;
}
//函数定义
Function name:
1. Return type
2. Number of formal parameters
a. Data Type of each formal parameter
b. Any local variables?
3. Task performaned
4. Comments
运行:
How many items did you eat today? 5
Eater the number of calories in each of the
5 items eaten:
Item 1: 234
Item 2: 456
Item 3: 789
Item 4: 125
Item 5: 100
Total calories eaten today = 1704
The average calories per item is 340.80
我自己写到循环的时候就不下去了,完全没有了逻辑概念, displayOutput函数里又套着calcCalories(number of items),逻辑想不清楚了。下面是我自己写的不带函数。结果没有任何问题。愁死了
#include<iostream>
using namespace std;
int main()
{
int i = 1;
intnumber_of_items, number_of_eachItem,calories_of_eachItem;
int total_calories = 0;
double average_calories;
cout << "How many items did you eat today? ";
cin >> number_of_items;
cout << "Enter the number of calories in each of the\n"
<< number_of_items << " items eaten:\n";
while (i <= number_of_items)
{
cout << "item " << i << ":";
i++;
cin >> calories_of_eachItem;
total_calories += calories_of_eachItem;
}
cout << "Total calories eaten today = " << total_calories << "\n";
average_calories = (static_cast<double>(total_calories))/ number_of_items;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The average calories per item is " << average_calories;
return 0;
}
本帖最后由 yuxijian2020 于 2021-3-24 10:20 编辑
我研究半天没懂你这需求里面哪里有什么函数套函数....
就单纯从第一个main函数来看,这就是写出3个函数的定义就完事了
#include <iostream>
using namespace std;
//函数声明
int getInput();
int calcCalories(int sum);
void displayOutput(int sum, int total);
int main ()
{
int number_of_items,total_calories;
number_of_items = getInput();
total_calories = calcCalories(number_of_items);
displayOutput(number_of_items, total_calories);
return 0;
}
int getInput()
{
int sum = 0;
printf_s("How many items did you eat today?\n");
cin >> sum;
//if(sum > 0) //不太确定你这是不是要有个判断
//{
return sum;
//}
}
int calcCalories(int sum)
{
int temp = 0;
int total = 0;
printf_s("Eater the number of calories in each of the %d items eaten:\n", sum);
for(int i = 1; i <= sum; ++i)
{
printf_s("Item %d: ", i);
cin >> temp;
total += temp;
}
return total;
}
void displayOutput(int sum, int total)
{
float average = (float)total / (float)sum;
printf_s("Total calories eaten today = %d\n", total);
printf_s("The average calories per item is %.2f\n", average);
} 谢谢大神。没有嵌套,只是我自己觉得好像有。但实际就是声明跟调用,我初学函数,感觉挺难的 我现在美国读书,学校封校,图书馆关闭,没有同学,老师根本就不细讲,照着教材弄几个破视频糊弄糊弄,也不带着做题。所以题见到的太少,没有针对性的练习,我现在感觉完全是自学考试,自修C++太痛苦了。您别笑话我:( 幸亏有这个平台
页:
[1]