You are on page 1of 2

Week 9

This week you will be using functions and random numbers.


Download the file tutor01.cpp from Moodle. It asks the user to give solutions
to either linear or quadratic equations.
If the user wants to practice linear equations it will ask, given numbers a and
b, what the solution is of equation

ax+ab=0

The solution to this equation is -b.

If the user wants to practice quadratic equations it will ask, given numbers a
and b what the solution is of equation
2
x + (a + b) x + a b = 0

The solutions to this equation are -a and -b. The user has to guess one of
these.

Programming Exercise 2.9.1 - Random numbers


When you compile and run the program tutor01.cpp you notice that it always
ask the same question and the number 0 is always a correct answer. Change
the program as follows:

The program should instead assign to each variable a and b a random


number between -10 and 10 at the beginning of the while-loop.

Set the random seed such that it selects different random numbers each time
you run the program. Set the seed only once in your program.

Compile, run, and test the program.

Paper Exercise 2.9.2 - Understanding functions


The program tutor01.cpp has two functions readint and signchar. Write for
each function a comment that explains the parameters of the function, what it
it computes and returns. Discuss on Forum (especially online students).

Programming Exercise 2.9.3 - Using Functions


The program (including the random numbers) has two problems that occur
when you are trying solving quadratic equations.

1. The first problem is that the program does not work if you do not enter a
number as answer (What does happen if you enter a letter 'x'?).
2. The other is that it will sometimes print formulas like:

What is a solution to x^2+ 8 x + -20 = 0

21
The term + -20 is wrong. It should read x^2 + 8 x - 20 = 0.

Use the two functions readint and signchar to fix those problem. Note, you do
not have to change those functions. You just have to use them at the
appropriate places in the program.
NB: fabs(x) returns the absolute value of x.
Programming Exercise 2.9.4 - Counting
The program tutor01.cpp does count the number of successful answer
(variable score), but does not count how many tries have been made. Add a
variable such that the program counts the number of tries, and prints at the
end the score and the number of tries.

You might also like