简体   繁体   中英

Need help understanding passing arguments to function

I'm new to C++ and unsure about how to pass arguments to functions.

I'm using a function Distance() to calculate the distance between two nodes. I declare the function like this:

int Distance(int x1, int y1, int x2 , int y2)
{   
    int distance_x = x1-x2;
    int distance_y = y1- y2; 
    int distance = sqrt((distance_x * distance_x) + (distance_y * distance_y));
    return distance; 
}

In the main memory I have 2 for loops. What I need to know is if I can pass the values like this: Distance (i, j, i+1, j+1) .

for(int i = 0; i < No_Max; i++)
{
    for(int j = 0; j < No_Max; j++)
    {
        if(Distance(i, j, i+1, j+1) <= Radio_Range) // the function 
            node_degree[i] = node_degree[i] + 1;

        cout << node_degree[i] << endl;
    }  
}

函数的参数可以作为与该参数的类型匹配的任何表达式提供,也可以强制转换为该参数。

Tips : You should use double instead of int if you want to use sqrt :

http://www.cplusplus.com/reference/clibrary/cmath/sqrt/

It looks as if you are calling your Distance(int, int, int, int) function correctly. The following statement will call Distance() :

Distance (i, j, i+1, j+1);

This will store the value returned by Distance() in a variable:

int dist = Distance (i, j, i+1, j+1);

This will compare the value returned by Distance() (the left operand) to Radio_Range (the right operand). If the left operand is less than or equal to the right operand, it will be evaluated to 1 (true). Otherwise it will be 0 (false). If the overall value of the expression inside the if statement is non-zero, the statement or block immediately following the if statement will be executed:

if(Distance(i, j, i+1, j+1) <= Radio_Range)
   //Statement;

or:

if(Distance(i, j, i+1, j+1) <= Radio_Range){
   //Statement;
   //Statement;
   //...
}

However, the value returned by Distance() will be truncated to an integer. Thus, distance will not equal the actual distance unless (distance_x * distance_x) + (distance_y * distance_y) is a perfect square. For better precision, consider using a double . If you intend to have the function return an int , it would be wise to do an explicit type cast, eg:

int distance = (int)sqrt((distance_x * distance_x) + (distance_y * distance_y));

This will ensure that if you or anyone else looks at the code later on, they will not think the function is using the wrong data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM