Exercise 4
Added Exercise 4 to respository with README Files
This commit is contained in:
16
Informatik_I/Exercise_4/Task_3/README.md
Normal file
16
Informatik_I/Exercise_4/Task_3/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Task
|
||||
|
||||
Implement the following rounding function that rounds a 64-bit floating point number (type `double`) to the nearest 32-bit integer (type `int`). You may assume that the type `double` complies with the IEEE standard 754. The function is only required to work correctly if the nearest integer is in the value range of the type `int`, otherwise, the return value of the function is undefined.
|
||||
|
||||
**Note: Usage of library rounding functions (standard or others) is not allowed.**
|
||||
|
||||
```cpp
|
||||
// PRE: x is roundable to a number in the value range of type @int@
|
||||
// POST: return value is the integer nearest to x, or the one further
|
||||
// away from 0 if x lies right in between two integers.
|
||||
int round_number(double x);
|
||||
```
|
||||
|
||||
Write your solution in `rounding.h`.
|
||||
|
||||
_Hint_: In `C++`, when you convert a `float` or `double` to an `int`, the fractional part gets cut off (truncated). Think about how you can use the truncated number to solve the exercise.
|
13
Informatik_I/Exercise_4/Task_3/rounding.h
Normal file
13
Informatik_I/Exercise_4/Task_3/rounding.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
// PRE: x is roundable to a number in the value range of type int
|
||||
// POST: return value is the integer nearest to x, or the one further
|
||||
// away from 0 if x lies right in between two integers.
|
||||
int round_number(double x) {
|
||||
int res;
|
||||
if (x < 0)
|
||||
res = x - 0.5;
|
||||
else
|
||||
res = x + 0.5;
|
||||
return res;
|
||||
}
|
Reference in New Issue
Block a user