diff --git a/1-ProceduralProgramming/3-Types.ipynb b/1-ProceduralProgramming/3-Types.ipynb index 323c8776e306e4b04ada2e428ad1c1893fbc44ec..9d1b8d9f42aab18fec05dab2657b61bd1dce9efc 100644 --- a/1-ProceduralProgramming/3-Types.ipynb +++ b/1-ProceduralProgramming/3-Types.ipynb @@ -533,6 +533,64 @@ "* `reinterpret_cast`, which is a very brutal cast which changes the type into any other type, regardless of the compatibility of the two types considered. It is a dangerous one that should be considered only in very last resort (usually when interacting with a C library)." ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Be wary of mathematical operators and types\n", + "\n", + "It was already covered in the Hands-On but please bear in mind that this operation: `2/3` is an integer division, so the result will be an `int`, and might not be what you want.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "cpp" + } + }, + "outputs": [], + "source": [ + "{\n", + " double a = 2 / 3;\n", + " std::cout << a << std::endl; // a == 0\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you really want a `float` division, you have to cast at least one of the value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "cpp" + } + }, + "outputs": [], + "source": [ + "{\n", + " double a = static_cast<float>(2) / 3;\n", + " std::cout << a << std::endl;\n", + " // this is also valid\n", + " double b = 2. / 3;\n", + " std::cout << b << std::endl;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Please note that the best would be to explicitly cast both values, to avoid useless implicit conversion." + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -1036,8 +1094,8 @@ "source": [ "\n", "[© Copyright](../COPYRIGHT.md) \n", - "", - "", + "\n", + "\n", "\n" ] }