/*
Defining functions. see Nyhoff P155-159
Code with loops or structures that are much larger than what can be shown on the screen are almost always wrong.
We can use functions to replace code by function calls, that makes code much faster and easier to read and
hence avoid making bugs.
Functions look like:
name( )
{
return ;
}
Some functions does not return any result, they are void
void name( )
{
}
Function can only return a single value. We will return to how to return multiple values later.
Hint always document that you aim for the function to do.
Exercise:
1) Write a boolean functions noRoots and oneRoot.
2) Write functions root1 and root2, that returns the two roots, or 0 if the root is undefined.
*/
#include
#include
using namespace std;
int times42(int n) // n and m only exists within { ... } the body of the function.
{
int m=n*42;
return m;
}
double discriminant(double a,double b,double c)
/*
Calculate discriminant of polynomium ax^2 + bx + c.
NB. a,b,c are copies of the caller, if you change them inside the function,
the original variables in main are not affected!
*/
{
double D=b*b-4.0*a*c;
return D;
}
bool twoRoots(double a,double b,double c)
/*
Return whether polynomium has two roots.
*/
{
bool has2roots = discriminant(a,b,c)>0;
return has2roots;
}
int main()
{
int n=3;
cout << times42(n) << "\n";
double a=5.5, b=1.0, c=2.0;
cout << discriminant(a,b,c) << "\n";
cout << twoRoots(a,b,c) << "\n";
return 0;
}