UDA 1.c++ function

Source: Internet
Author: User

Functions: Python vs C + +

In Python and C + +, functions work the same way, and functions combine statements to perform certain tasks. Functions can help you avoid duplicating and pasting the same code repeatedly.

The syntax for writing a function is somewhat different, with three main reasons:

    1. Python detects the end of a line of code by looking at a carriage return and a newline character. C + + uses semicolons to implement this functionality.
    2. Python uses indentation to group code statements together, but C + + uses curly braces.
    3. Python is a dynamic type, and C + + is a static type. As with declaring a variable, you also need to declare your function.

Let's start with a simple function and compare Python and C + + code side-by-side.

This function is substituting speed and time. The distance is calculated by multiplying the two. In addition to the grammatical differences, pay special attention to:

    • function declaration
    • Variable declaration
    • What code is inside main () and what code is external.
Anatomy code

C + + code looks much longer than Python code because C + + has some extra parts. We parse the code step by step.

The code starts with

# include <iostream>

Here is the iostream section of the import C + + standard library. This line of code is required to use cout .

After importing the necessary libraries, you can see a function declaration.

float distance(float velocity, float time_elapsed);

This line of code notifies your C + + program that there is a function called distance. This function receives two single-precision floating-point numbers and returns a single-precision floating-point number. The first single-precision floating-point number is velocity, and the second is time_elapsed.

Then the main function. All C + + programs require the main () function, which returns 0. Main () calls the distance function and outputs the result to the terminal.

int main() {    std::cout << distance(5, 4) << std::endl; std::cout << distance(12.1, 7.9) << std::endl; return 0;}

And finally the function definition.

float distance(float velocity, float time_elapsed) { return velocity * time_elapsed;}

You've seen the main () function before, so this isn't the first time you've seen how a function works in C + +. Note that the main function and the syntax of the distance function are very similar. The only difference is that the main function does not accept any arguments and returns an integer with a value of 0, whereas the distance function accepts two single-precision floating-point numbers and returns a single-precision floating-point number.

In addition, the main function does not need to be declared separately.

function anatomy

You've seen how to write a function in C + +. Generally speaking, C + + functions consist of function declarations and function definitions.

Because C + + is statically typed, you need to specify the data type of the function input variable and the data type returned by the function.

// function Declaration returndatatype functionname (datatype variable_a, datatype variable_b, etc); // function Definition returndatatype functionname (datatype variable_a, datatype variable_b, etc.) {     statement_1;     statement_2;     .   ... etcreturn  Returndatatype}
Small test: Writing a function

Write a function called distance, which has 3 inputs and one output. Input is speed, acceleration, and time. The output is the distance elapsed over time. The distance is calculated as:Distance = velocity \times elapsedtime + 0.5 \times acceleration \times elapsedtime \times elapsedtimeDISTANCE=VELOCITYXELAPSEDTIME+0.5XACCELERatio< Span class= "Mord mathit" >nxelapse dtim< Span class= "Mord mathit" >exelapse dtim< Span class= "Mord mathit" >e

//Todo:include the iostream part of the library#include <iostream>//Todo:declare your function called distancefloatDistancefloatVelocityfloatAcceleration,floattime_elapsed);//Leave The main function as isintMain () {//todo:the Following is examples you can use to test your code. //You'll need to uncomment them to get them working.Std::cout<< Distance (3,4,5) <<Std::endl; Std::cout<< Distance (7.0,2.1,5.4) <<Std::endl; return 0; }//Todo:define your functionfloatDistancefloatVelocityfloatAcceleration,floattime_elapsed) {    returnVelocity*time_elapsed +0.5*acceleration*time_elapsed*time_elapsed;}
Multi-output functions

In Python, you can write multiple output functions. For example, the following:

## Python Codedef distance(velocity, time_elapsed): return velocity * time_elapsed, velocity / 2

It will output elocity time_elapsed as well as VELOCITY/2 (speed time and speed/2).

in C + +, a function can have only one output. Of course we have some workarounds, but these scenarios are not covered by this module.

C + + tips: function declarations

You don't need to put a function declaration at the beginning of the code to get a valid solution. Just as you can declare and define a variable at the same time, int x = 5; you can declare and define a function at the same time.

The following code can also be run:

float distance (floatfloat  time_elapsed) {    return velocity *  time_elapsed;} int Main () {    << distance (54) << Std::endl;     << distance (12.17.9) << Std::endl;     return 0 ;}

Note, however, that you need to define your function before the main () function, not after it, or your code will attempt to invoke the distance () function without its definition.

UDA 1.c++ function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.