Home  >  Article  >  Backend Development  >  Examples of usage of C++ functions

Examples of usage of C++ functions

PHPz
PHPzOriginal
2024-04-11 13:36:02877browse

C functions provide code reuse. They can accept parameters, return results, and break complex tasks into small units. A function declaration specifies the name, parameters, and return type; a function definition provides the actual implementation. When calling a function, use the function name and actual parameters. Example: Function calculates the average of a number, accepts a vector argument, and returns the average.

C++ 函数的用途举例

Examples of usage of C functions

Functions are the basic building blocks for code reuse in C. They allow you to group blocks of code into a named unit for reuse within your program. Functions can take parameters and return results, allowing you to break complex tasks into smaller, manageable parts.

Function declaration

The function declaration specifies the name, parameters, and return value type of the function. For example, the following declares a function named add that accepts two integer arguments and returns their sum:

int add(int a, int b);

Function Definition

The function definition provides the actual implementation of the function. It specifies the code in the body of the function that will perform the task that is performed when the function is called. For example, the following defines the add function:

int add(int a, int b) {
  return a + b;
}

Function call

To call a function, use the function name followed by a set of actual parameter. For example, the following code calls the add function, taking 5 and 10 as parameters:

int result = add(5, 10);

Practical case: Using the function to calculate the average Value

The following code demonstrates how to use a function to calculate the average of a set of numbers:

#include <iostream>
#include <vector>

using namespace std;

double average(vector<double> numbers) {
  double sum = 0;
  for (int i = 0; i < numbers.size(); i++) {
    sum += numbers[i];
  }
  return sum / numbers.size();
}

int main() {
  vector<double> values = {12.3, 23.5, 34.7, 45.9, 56.1};
  double avg = average(values);
  cout << "Average: " << avg << endl;
  return 0;
}

In this example, the average function accepts a double Parameters to a vector of values ​​and calculates their average. This function is then called within the main function with a set of numbers as input. The output will be the average of these numbers.

The above is the detailed content of Examples of usage of C++ functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn