Mathematical functions are similar, but not quite the same as functions in C++.
y = f(x)where
f(x) = x2
will produce a value if we give a value for x. For example,
y = f(3) = 9 y = f(4) = 16 y = f(5) = 25 y = f(3) = 9
If the same value for x is given to a mathematical function, it always gives the same result.
y = f();
At line 17,
argument
|
|
y = sqrt( i );
| |
+-------+
|
function call
1 #include <iostream>
2 #include <iomanip>
3 #include <cmath>
4
5 using namespace std;
6
7 int main()
8 {
9 double y;
10
11 cout.setf(ios::fixed);
12 cout.precision(4);
13
14 cout << setw(10) << "Number"
15 << setw(13) << "Square Root" << endl;
16 for(int i = 1; i <= 10; i++) {
17 y = sqrt((double) i);
18 cout << setw(10) << i
19 << setw(13) << y << endl;
20 }
21
22 cout << endl << endl;
23 return 0;
24 }
The C/C++ libraries have many predefined functions you can use in your program.
You generally need to include one or more header files (with the #include directive) to use these functions.
The <cmath> header includes the declaration
of the sqrt function used in the example and the
pow function that computes powers of a
value.
sqrt function is declared in the
<cmath> header and it is defined in the library.You can write your own functions
The code for a function can serve as both the declaration and the defintion.
As for variables, if you are to going to call your function, it must be declared before the point that it is called.
The function definition can occur in a file after the
main function that calls it, but a declaration must
come before it is called.
return_type function_name ( argument_list ) {
local declarations
initializations
processing statements
return statement
}
where the expression is of the same type as the declared return_type (or at least can be converted implicitly to that type).return expression;
Here is the example program that computed square roots without using the predefined sqrt function:
1 int main()
2 {
3
4 double x, y;
5 cout << "Enter a positive number: ";
6 cin >> x;
7
8 y = ( 1.0 + x ) /2;
9
10 while( fabs(x - y * y) > 0.0001 ) {
11 y = (y + x/y)/2;
12 }
13 cout.setf(ios::fixed);
14 cout.precision(4);
15
16 cout << "x = " << x << endl;
17 cout << "y = " << y << endl;
18 cout << "y*y = " << y * y << endl;
19
20 return 0;
21 }
(In class)