难以理解某个函数的元素是如何工作的

Trouble understanding how elements of a certain function work

本文关键字:何工作 工作 元素 函数      更新时间:2023-10-16

我需要完全理解以下代码:

#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_takentime()函数中得到其值: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_lengthd_plot_width等的值。因此,我无法理解编译器如何知道这些值p_areah_area的实际值。

我意识到area()函数在某种程度上被用来帮助time()函数,但据我所知,time()函数中的变量P_area等没有分配值。

请有人填补我理解上的空白。

更确切地说,我想知道time_taken从流程开始到cout在屏幕上是如何显示的。就像我说的,我熟悉大多数领域,但不是所有领域。

在您的程序中,您计算了以下值:

plot_area=面积(d_plot_length,d_plot_width);home_area=区域(d_home_side,d_home_sde);

当方法area(double,double)被调用时,结果double值被存储在这些变量中。

然后进行函数调用:time_taken = time(plot_area, home_area, d_mow_rate);

这是按值调用类型的函数调用。变量plot_areahome_aread_mow_rate中的值的副本被传递给函数。在time(double, double, double)中,计算是基于您在此方法中定义的逻辑进行的,结果值将返回给main()方法中的函数调用。

请注意,函数调用为call by value,因此,即使main()和函数调用中的变量名称相同,也只会将值的副本传递给函数time(double, double, double)中提到的参数。

为了进一步阅读,我建议你看看以下链接:

  1. 呼叫方价值
  2. 呼叫方参考
  3. 呼叫方指针