MATH49111/69111: Scientific Computing: 2nd October 2017
MATH49111/69111: Scientific Computing: 2nd October 2017
Lecture 3
2nd October 2017
Dr Chris Johnson
[email protected]
Outline
int main()
{
std::cout << power(5.0, 2) << std::endl;
std::cout << power(3.0, 3) << std::endl;
return 0;
}
A return statement
. specifies the value that the function evaluates to (this return
value is of type [return_type])
. exits the function and returns to the code that called it
Defining functions
[return_type] [function name]([parameters])
{
[function body]
.[return_statement]
}
int main()
{
std::cout << Maximum(3, 5) << std::endl; // function call
return 0;
}
Function declarations
Functions must be declared in code before they are called
. …or the declaration (or prototype) can be put above the place
that the function is called, and the function definition below:
// function declaration: no function body, and a semicolon
int Maximum(int a, int b);
int main()
{
std::cout << Maximum(3, 5) << std::endl; // function call
return 0;
}
int main()
{
// declare a variable of type std::ofstream named 'file'
std::ofstream demoFile;
Output:
1 3.56 0.356735
1.234 3.56 0.356735
Formatting output streams
The way that std::cout and other output streams display
(floating-point and integer) numbers can be customised:
. Number of significant figures:
double pi = 3.14159265358969323;
std::cout.precision(5);
std::cout << pi << std::endl;
std::cout.precision(15);
std::cout << pi << std::endl;
Output:
3.1416
3.14159265358969
int main()
{
int a;
std::cout << "Enter a number: ";
std::cout << a << "^2" << "=" << (a*a) << std::endl;
return 0;
}
Input streams
. We can read more than one variable at once:
int a; double b;
std::cin >> a >> b;
. What if the input is not a valid number? We can check this with
int a; double b;
if (std::cin >> a >> b)
{
// a and b have been read
}
else
{
// a or b could not be read correctly
}
Reading from files
Coursework 1:
. Now set, see ‘Coursework & Projects’ section on course website
. Due in 9th October, 5pm, through Blackboard
. No more than 1–2 pages
. Can use LATEX or Word, and any software for graphs (Excel,
MATLAB etc.). See LATEX template and instructions on making
graphs in MATLAB/Gnuplot on course website.