我需要完全理解以下代码:
#include <iostream>
using namespace std;
double area(double length, double width);
double time(double p_area, double h_area, double mow_rate);
int main() {
double d_plot_length, d_plot_width, d_home_side, d_mow_rate;
double plot_area, home_area, time_taken;
// I've used double for all of these to get the most precise values possible, something I'd only really consider doing on small programmes such as this
cout << "What is the length of the plot? In meters please." << endl;
cin >> d_plot_length;
cout << "What is the width of the plot? In meters please." << endl;
cin >> d_plot_width;
cout<< "What is the size of the side of the house? In meters please." << endl;
cin >> d_home_side;
cout << "What is the rate at which you are going to be mowing? In meters per minute please" << endl;
cin >> d_mow_rate;
// Just getting all the data I need from the user
plot_area = area(d_plot_length, d_plot_width);
home_area = area(d_home_side, d_home_side);
time_taken = time(plot_area, home_area, d_mow_rate);
cout << "It will take " << time_taken << " minutes to mow this lawn. Better get cracking" << endl;
return 0;
}
double area(double length, double width) {
double value;
value = length * width;
return value;
}
double time(double p_area, double h_area, double mow_rate) {
double value;
value = (p_area - h_area) / mow_rate;
return value;
}
我很难理解 time()
函数的工作原理。
到目前为止我的理解是:
time_taken
,从 time()
函数获取其值:time(plot_area, home_area, d_mow_rate)
。
time()
函数从底部的函数声明中获取它的值。
double time(double p_area, double h_area, double mow_rate) {
double value;
value = (p_area - h_area) / mow_rate;
return value;
}
但是,这就是我卡住的地方。要求用户输入 d_plot_length
、d_plot_width
等的值。所以我无法理解编译器如何知道这些值 p_area
和 h_area
其实都是。
我意识到 area()
函数以某种方式被用来辅助 time()
函数,但据我所知,变量
等没有分配给它们的值。time()
函数中的 P_area
请有人填补我理解中的空白。
更准确地说,我想知道从进程开始到cout
,time_taken
是如何显示在屏幕上的。就像我说的,我熟悉大多数领域,但不是全部。
最佳答案
在您的程序中,您计算了以下值:
plot_area = area(d_plot_length, d_plot_width); home_area = area(d_home_side, d_home_side);
当调用方法 area(double,double)
时,生成的 double
值将存储在这些变量中。
然后你有函数调用:
time_taken = time(plot_area, home_area, d_mow_rate);
这是函数调用的按值调用类型。变量 plot_area
、home_area
和 d_mow_rate
中值的拷贝被传递给函数。在 time(double, double, double)
中,计算是根据您在此方法中定义的逻辑完成的,结果值返回到 main( )
方法。
请注意函数调用是按值调用
,因此只有值的拷贝被传递给函数time(double, double, double)
即使 main()
和函数调用中的变量名称相同。
为了进一步阅读,我建议您查看以下链接:
关于c++ - 难以理解某个功能的元素如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609264/