Вы находитесь на странице: 1из 2

MATH49111/MATH69111

Examples Sheet 1

Basic Syntax
Make sure that you include, at least, some comments in your code.

1.1 Write the classic hello world program a program that prints the text string “hello
world” (or any other string you like).

1.2 Write a program to calculate the area and circumference of a circle of radius 5.0.
Change the code so that the radius may be specified by the user.

1.3 DEBUG the programs off my website...

Data Types
1.4 Calculate the value of π using the expression

π = 4 tan−1 (1),

and store it as a float, double and a long double. Use the function atan() from
the cmath library for tan−1 (). Print out the value of each setting precision and width
of the object cout using the commands:

c o u t << s e t p r e c i s i o n ( 3 2 ) ;
c o u t . width ( 3 2 ) ;

You will need to include the library iomanip to set precision.

1.5 Write a program containing the following:


double x =1.56 , y = 2 . 6 7 ;
int a=2,b=5;
c o u t << ” a∗x=” << a ∗x << ” x/y=” << x/y << ” a /b=” << a/b << e n d l ;

Are the results what you would expect? How can we change last expression to get a
fraction?

1
1.6 Try inputting the following statement:
int n=3.8 + 3 . 8 ;

What are the possible values n could take? What is the results you get? What is the
order of operations and conversions.

1.7 We have a set of grid points defined by:

xi = xmin + idx, xmin = −0.5, dx = 0.01, i = 0, 1, 2, . . . , 100

Write a program to find the nearest grid point (an integer) to x = 0.3467. Rewrite
the program to allow the user to specify the value of x. What happens when x < −0.5?
How can you give a sensible answer?

File I/O
1.8 Write down the first two terms in the Maclaurin series for exp(x).

1.9 Write a program to put data into the file ‘data.csv’. You must generate four columns
of data to enter into the file: the value of x, the numeric solution for exp(x), the
two term Maclaurin series approximation to exp(x), and the difference between the
numeric solution and the approximation. Generate data for at least 50 values of x in
the range x ∈ [−0.5, 0.5]. Use a comma to separate columns, you will need to use a
for loop to create rows of data.

1.10 Create a figure plotting both the numeric solution and the Maclaurin approximation
against x. You may use either:

(i) a spreadsheet application to draw charts from the data;


(ii) matlab to import the data and create plots;
(iii) or gnuplot the write a plot file and create the figure.

Вам также может понравиться