From 041409a1b84af3b121674846f79a53978899a719 Mon Sep 17 00:00:00 2001 From: Fabien Vergnet <fabien.vergnet@math.u-psud.fr> Date: Thu, 20 May 2021 20:53:01 +0200 Subject: [PATCH] add exercice2 --- TP/1-ProceduralProgramming/exercice2.cpp | 53 ++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 TP/1-ProceduralProgramming/exercice2.cpp diff --git a/TP/1-ProceduralProgramming/exercice2.cpp b/TP/1-ProceduralProgramming/exercice2.cpp new file mode 100644 index 0000000..2139f26 --- /dev/null +++ b/TP/1-ProceduralProgramming/exercice2.cpp @@ -0,0 +1,53 @@ +#include <iostream> +#include <cmath> // for std::round + + +//! Returns `number` * (2 ^ `exponent`) +int times_power_of_2(int number, int exponent) +{ + while (exponent > 0) + { + number *= 2; + exponent -= 1; + } + while (exponent < 0) + { + number /= 2; + exponent += 1 ; + } + + return number; +} + + +//! Round to `x` the nearest integer. +int round_as_int(double x) +{ + return static_cast<int>(std::round(x)); +} + + + +/************************************/ +// Main function +/************************************/ + +int main(int argc, char** argv) +{ + static_cast<void>(argc); // to silence warning about unused argc - don't bother + static_cast<void>(argv); // to silence warning about unused argv - don't bother + + int numerator1 = round_as_int(0.65 * times_power_of_2(1, 1)); + std::cout << "0.65 ~ " << numerator1 << " / 2^1" << std::endl ; + + int numerator2 = round_as_int(0.65 * times_power_of_2(1, 2)); + std::cout << "0.65 ~ " << numerator2 << " / 2^2" << std::endl ; + + int numerator3 = round_as_int(0.65 * times_power_of_2(1, 3)); + std::cout << "0.65 ~ " << numerator3 << " / 2^3" << std::endl ; + + std::cout << std::endl ; + + return EXIT_SUCCESS; +} + -- GitLab