Quiz #3

Hey guys!

I had my quiz #3 and I want to share it with you. I had to make two different codes and these are the instruction:

1)

Write a function called distance(x1, y1, x2, y2) which receives four numbers which represent two points in the cartesian plane. The function should return the distance between the two points (x1,y1) and (x2,y2). Remember that the square of the hypotenuse of a right angle triangle is equal to the sum of the squares of the two other sides.

Here’s my code:

2016-02-13

It is not a difficult code because we only have to use a common formula used commonly in math and physics. We have to adapt it in a way the code can get it. We need to declare 2 points in the cartesian plane that’s why we have to use 4 different variables.

NOTES:

  • Use float for non-integer numbers for more accuracy.
  • As you can see we are using another library calls <cmath> because we have to use a square root and it is represented by “sqrt()”.

2)

Write a function called fibonacci which receives a single parameter “n” (a non-negative integer) and returns the nth number in the fibonacci series which is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89…………

So, fibonacci(0) would return 0. fibonacci(5) would return 5 fibonacci(8) would return 21.

Note that the first two fibonacci numbers are 0 and 1. All others are the sum of the previous two fibonacci numbers.

Here’s my code:

2016-02-13 (1)
2016-02-13 (2)

For definition the fibonacci number is a series of whole numbers in which each number is the sum of the two preceding numbers. Beginning with 0 and 1, the sequence of Fibonacci numbers would be 0,1,1, 2, 3, 5, 8, 13, 21, 34, etc. using the formula n =

+ n(-2), where the n(-1) means “the last number before n in the series” and n(-2) refers to “the second last one before n in the series.” (http://www.webopedia.com/TERM/F/Fibonacci_numbers.html).

Knowing the definition and the formula we can do the code easily. First we have to condition that if the user introduce “0” or “1” the result is “0” or “1” respectively. The other numbers are going to be used in the formula “n(-1) + n(-2)” so the answer will be the number in the choosen place.

 

For the first code I didn’t have problems to make it because I know the formula and how the code can work with it. But for the second code I had to consult information to understand how to do it. This page was good for me.

First code.

Second code.

Practice the codes and comment if you have some doubt.

See you in my next post!

Top image by: https://www.tumblr.com/search/pitagoras

 

 

 

 

 

CC BY-SA 4.0 Quiz #3 by sercho93 is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.