无法理解某个功能的元素是如何工作的

时间:2016-04-13 20:46:28

标签: c++ visual-studio visual-c++ visual-studio-2015

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

#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_lengthd_plot_width等的值。因此,我无法理解编译器如何知道这些值p_areah_area实际上是什么。

我意识到area()函数在某种程度上用于帮助time()函数,但据我所知P_area中的变量time()等函数没有赋值给它们。

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

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

1 个答案:

答案 0 :(得分:1)

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

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_areahome_aread_mow_rate将传递给函数。在time(double, double, double)中,计算是在您在此方法中定义的逻辑的基础上完成的,并且结果值将返回到main()方法中的函数调用。

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

如需进一步阅读,我建议您查看以下链接:

  1. Call By Value
  2. Call By Reference
  3. Call By Pointer