{"id":212,"date":"2026-03-19T12:23:28","date_gmt":"2026-03-19T12:23:28","guid":{"rendered":"https:\/\/sites.wsagames.com\/jl9u24\/?p=212"},"modified":"2026-03-19T13:05:50","modified_gmt":"2026-03-19T13:05:50","slug":"math-in-c","status":"publish","type":"post","link":"https:\/\/sites.wsagames.com\/jl9u24\/2026\/03\/19\/math-in-c\/","title":{"rendered":"Math in C++"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Previously I have learned the basics on starting and ending a code including the basic data types.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td>Data type<\/td><td>Size (byte)<\/td><td>Description<\/td><\/tr><tr><td><code>boolean<\/code><\/td><td>1<\/td><td>Stores true or false values<\/td><\/tr><tr><td><code>char<\/code><\/td><td>1<\/td><td>Stores a single character\/letter\/number or ASCII values<\/td><\/tr><tr><td><code>int<\/code><\/td><td>2 or 4<\/td><td>Stores whole numbers, without decimals<\/td><\/tr><tr><td><code>float<\/code><\/td><td>4<\/td><td>Stores fractional number, containing one or more decimals. Sufficient for storing 6-7 decimal digits<\/td><\/tr><tr><td><code>double<\/code><\/td><td>8<\/td><td>Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Using these I can use it for simple maths.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By using int when I need to store a whole number without decimals, I can store numbers such as 25, 1000, or even 210981324.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">and float or double for &#8220;floating&#8221; point numbers like 9.99 or 3.14159265<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int myNum = 1000;\ncout &lt;&lt; myNum;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>float myNum = 5.5;\ncout &lt;&lt; myNum;\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>double myNum = 3.1415;\ncout &lt;&lt; myNum;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>float<\/code> vs <code>double<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of <code>float<\/code> is only six or seven decimal digits, while <code>double<\/code> variables have a precision of about 15 digits. Therefore it is safer to use <code>double <\/code>for most calculations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A floating point number can also be a scientific number with an &#8220;e&#8221; to indicate the power of 10<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>float f1 = 35e3;\ndouble d1 = 12E4;\ncout &lt;&lt; f1;\ncout &lt;&lt; d1;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Max and Min<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>max(x,y)<\/code> function can be used top find the highest value of x and y<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cout &lt;&lt; max(5, 10);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">and the <code>min(x,y)<\/code> function can be used to find the lowest value of x and y<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cout &lt;&lt; min(5, 10);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">C++ &lt;cmath&gt; library<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Other functions such as sqrt (square root), <code>round <\/code>(rounds a number) and <code>log <\/code>(natural logarithm) can be found in the <code>&lt;cmath&gt;<\/code> header file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Include the cmath library\n#include &lt;cmath&gt;\n\ncout &lt;&lt; sqrt(64);\ncout &lt;&lt; round(2.7);\ncout &lt;&lt; log(2);\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Building a Calculator<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;   \/\/ For input\/output operations (cin, cout)\n#include &lt;limits&gt;     \/\/ For numeric_limits (handling input errors)\n#include &lt;cmath&gt;      \/\/ For mathematical functions (pow, sqrt, etc.)\n\nusing namespace std;  \/\/ Allows us to use standard library names without std:: prefix\n\n\/\/ Function to display the calculator menu\nvoid displayMenu() {\n    cout &lt;&lt; \"\\n=== SIMPLE CALCULATOR ===\\n\";\n    cout &lt;&lt; \"1. Addition (+)\\n\";\n    cout &lt;&lt; \"2. Subtraction (-)\\n\";\n    cout &lt;&lt; \"3. Multiplication (*)\\n\";\n    cout &lt;&lt; \"4. Division (\/)\\n\";\n    cout &lt;&lt; \"5. Power (^)\\n\";\n    cout &lt;&lt; \"6. Square Root (\u221a)\\n\";\n    cout &lt;&lt; \"7. Exit\\n\";\n    cout &lt;&lt; \"Enter your choice (1-7): \";\n}\n\n\/\/ Function to get a valid number from user\ndouble getNumber(string prompt) {\n    double num;\n    while (true) {\n        cout &lt;&lt; prompt;\n        cin &gt;&gt; num;\n        \n        \/\/ Check if input failed (user entered non-numeric)\n        if (cin.fail()) {\n            cin.clear(); \/\/ Clear error flag\n            cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\\n'); \/\/ Discard invalid input\n            cout &lt;&lt; \"Invalid input! Please enter a number.\\n\";\n        } else {\n            cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\\n'); \/\/ Clear input buffer\n            return num;\n        }\n    }\n}\n\n\/\/ Function to perform addition\ndouble add(double a, double b) {\n    return a + b;  \/\/ Simply return sum\n}\n\n\/\/ Function to perform subtraction\ndouble subtract(double a, double b) {\n    return a - b;  \/\/ Simply return difference\n}\n\n\/\/ Function to perform multiplication\ndouble multiply(double a, double b) {\n    return a * b;  \/\/ Simply return product\n}\n\n\/\/ Function to perform division with error checking\ndouble divide(double a, double b) {\n    if (b == 0) {  \/\/ Check for division by zero\n        cout &lt;&lt; \"Error: Division by zero is not allowed!\\n\";\n        return 0;  \/\/ Return 0 as default value\n    }\n    return a \/ b;  \/\/ Return quotient\n}\n\n\/\/ Function to calculate power\ndouble power(double base, double exponent) {\n    return pow(base, exponent);  \/\/ Use cmath's pow function\n}\n\n\/\/ Function to calculate square root with error checking\ndouble squareRoot(double num) {\n    if (num &lt; 0) {  \/\/ Check for negative numbers\n        cout &lt;&lt; \"Error: Cannot calculate square root of negative number!\\n\";\n        return 0;  \/\/ Return 0 as default value\n    }\n    return sqrt(num);  \/\/ Use cmath's sqrt function\n}\n\nint main() {\n    int choice;           \/\/ Variable to store user's menu choice\n    double num1, num2;    \/\/ Variables to store operands\n    double result;        \/\/ Variable to store calculation result\n    \n    cout &lt;&lt; \"Welcome to the C++ Calculator!\\n\";\n    \n    \/\/ Main program loop - continues until user chooses to exit\n    while (true) {\n        displayMenu();  \/\/ Show menu options\n        cin &gt;&gt; choice;  \/\/ Get user's choice\n        \n        \/\/ Check if menu input is valid\n        if (cin.fail()) {\n            cin.clear();\n            cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\\n');\n            cout &lt;&lt; \"Invalid choice! Please enter a number.\\n\";\n            continue;  \/\/ Skip rest of loop and start over\n        }\n        \n        \/\/ Handle exit option\n        if (choice == 7) {\n            cout &lt;&lt; \"Thank you for using the calculator. Goodbye!\\n\";\n            break;  \/\/ Exit the while loop, ending the program\n        }\n        \n        \/\/ Process calculator operations based on user's choice\n        switch(choice) {\n            case 1:  \/\/ Addition\n                cout &lt;&lt; \"\\n--- ADDITION ---\\n\";\n                num1 = getNumber(\"Enter first number: \");\n                num2 = getNumber(\"Enter second number: \");\n                result = add(num1, num2);\n                cout &lt;&lt; num1 &lt;&lt; \" + \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                break;\n                \n            case 2:  \/\/ Subtraction\n                cout &lt;&lt; \"\\n--- SUBTRACTION ---\\n\";\n                num1 = getNumber(\"Enter first number: \");\n                num2 = getNumber(\"Enter second number: \");\n                result = subtract(num1, num2);\n                cout &lt;&lt; num1 &lt;&lt; \" - \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                break;\n                \n            case 3:  \/\/ Multiplication\n                cout &lt;&lt; \"\\n--- MULTIPLICATION ---\\n\";\n                num1 = getNumber(\"Enter first number: \");\n                num2 = getNumber(\"Enter second number: \");\n                result = multiply(num1, num2);\n                cout &lt;&lt; num1 &lt;&lt; \" * \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                break;\n                \n            case 4:  \/\/ Division\n                cout &lt;&lt; \"\\n--- DIVISION ---\\n\";\n                num1 = getNumber(\"Enter dividend: \");\n                num2 = getNumber(\"Enter divisor: \");\n                result = divide(num1, num2);\n                if (num2 != 0) {  \/\/ Only display result if division was valid\n                    cout &lt;&lt; num1 &lt;&lt; \" \/ \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                }\n                break;\n                \n            case 5:  \/\/ Power\n                cout &lt;&lt; \"\\n--- POWER ---\\n\";\n                num1 = getNumber(\"Enter base: \");\n                num2 = getNumber(\"Enter exponent: \");\n                result = power(num1, num2);\n                cout &lt;&lt; num1 &lt;&lt; \" ^ \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                break;\n                \n            case 6:  \/\/ Square Root\n                cout &lt;&lt; \"\\n--- SQUARE ROOT ---\\n\";\n                num1 = getNumber(\"Enter number: \");\n                result = squareRoot(num1);\n                if (num1 &gt;= 0) {  \/\/ Only display result if input was valid\n                    cout &lt;&lt; \"\u221a\" &lt;&lt; num1 &lt;&lt; \" = \" &lt;&lt; result &lt;&lt; \"\\n\";\n                }\n                break;\n                \n            default:  \/\/ Invalid menu choice\n                cout &lt;&lt; \"Invalid choice. Please select 1-7.\\n\";\n        }\n        \n        cout &lt;&lt; \"\\nPress Enter to continue...\";\n        cin.get();  \/\/ Wait for user to press Enter\n    }\n    \n    return 0;  \/\/ Program ended successfully\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Detailed Explanation<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Header Files (Lines 1-3)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>#include &lt;iostream&gt;<\/code>: Includes input\/output stream library for console operations<\/li>\n\n\n\n<li><code>#include &lt;limits&gt;<\/code>: Provides&nbsp;<code>numeric_limits<\/code>&nbsp;for handling input buffer sizes<\/li>\n\n\n\n<li><code>#include &lt;cmath&gt;<\/code>: Includes mathematical functions like&nbsp;<code>pow()<\/code>&nbsp;and&nbsp;<code>sqrt()<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using Namespace (Line 5)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>using namespace std;<\/code>: Allows direct use of standard library elements without&nbsp;<code>std::<\/code>&nbsp;prefix<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>displayMenu() Function (Lines 8-16)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Simple function that displays calculator options<\/li>\n\n\n\n<li>Uses&nbsp;<code>cout<\/code>&nbsp;to print formatted menu to console<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>getNumber() Function (Lines 19-34)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Purpose<\/strong>: Safely gets numeric input from user with error handling<\/li>\n\n\n\n<li><strong>While loop<\/strong>: Continues until valid input is received<\/li>\n\n\n\n<li><strong>cin.fail()<\/strong>: Checks if input stream failed (non-numeric input)<\/li>\n\n\n\n<li><strong>cin.clear()<\/strong>: Clears error flags on input stream<\/li>\n\n\n\n<li><strong>cin.ignore()<\/strong>: Discards invalid characters from input buffer<\/li>\n\n\n\n<li><strong>Return<\/strong>: Validated number as double<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Mathematical Functions (Lines 37-66)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>add(), subtract(), multiply()<\/strong>: Simple arithmetic operations<\/li>\n\n\n\n<li><strong>divide()<\/strong>: Includes division by zero check<\/li>\n\n\n\n<li><strong>power()<\/strong>: Uses&nbsp;<code>pow()<\/code>&nbsp;from cmath library<\/li>\n\n\n\n<li><strong>squareRoot()<\/strong>: Checks for negative numbers before using&nbsp;<code>sqrt()<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>main() Function &#8211; Variables (Lines 69-71)<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>choice<\/code>: Stores menu selection<\/li>\n\n\n\n<li><code>num1, num2<\/code>: Store operands for calculations<\/li>\n\n\n\n<li><code>result<\/code>: Stores calculation result<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Main Program Loop (Lines 76-143)<\/strong><\/h3>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Display menu<\/strong>&nbsp;and get user choice<\/li>\n\n\n\n<li><strong>Validate input<\/strong>&nbsp;using&nbsp;<code>cin.fail()<\/code><\/li>\n\n\n\n<li><strong>Check for exit<\/strong>&nbsp;(choice == 7)<\/li>\n\n\n\n<li><strong>Switch statement<\/strong>: Processes different operations based on choice<\/li>\n\n\n\n<li><strong>Each case<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Shows operation title<\/li>\n\n\n\n<li>Gets numbers using&nbsp;<code>getNumber()<\/code><\/li>\n\n\n\n<li>Performs calculation<\/li>\n\n\n\n<li>Displays result with proper formatting<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Default case<\/strong>: Handles invalid choices<\/li>\n\n\n\n<li><strong>Pause<\/strong>: Waits for Enter key before continuing<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Error Handling Features<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Division by zero<\/strong>&nbsp;detection<\/li>\n\n\n\n<li><strong>Negative square root<\/strong>&nbsp;detection<\/li>\n\n\n\n<li><strong>Invalid numeric input<\/strong>&nbsp;handling<\/li>\n\n\n\n<li><strong>Invalid menu choice<\/strong>&nbsp;handling<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Key Concepts:<\/h2>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Functions<\/strong>: Modular code organization<\/li>\n\n\n\n<li><strong>Input validation<\/strong>: Preventing crashes from bad input<\/li>\n\n\n\n<li><strong>Switch statements<\/strong>: Clean menu handling<\/li>\n\n\n\n<li><strong>Loops<\/strong>: Continuous operation until exit<\/li>\n\n\n\n<li><strong>Error handling<\/strong>: Graceful error messages<\/li>\n\n\n\n<li><strong>Mathematical operations<\/strong>: Using cmath functions<\/li>\n\n\n\n<li><strong>User interface<\/strong>: Clear prompts and formatted output<\/li>\n<\/ol>\n\n\n\n<p class=\"has-small-font-size wp-block-paragraph\">Claude ai was used for any helps and adjustments<br>Code was copied and pasted from my own cLion project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">If you want to view the code:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go here:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/onecompiler.com\/cpp\">https:\/\/onecompiler.com\/cpp<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Download this: <a href=\"https:\/\/drive.google.com\/file\/d\/1BbRHlHsXpo7xhx68MiqD2pkLzGORU0bg\/view?usp=drive_link\">https:\/\/drive.google.com\/file\/d\/1BbRHlHsXpo7xhx68MiqD2pkLzGORU0bg\/view?usp=drive_link<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And paste it to the compiler<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then click run<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Previously I have learned the basics on starting and ending a code including the basic data types. Data type Size (byte) Description boolean 1 Stores true or false values char 1 Stores a single character\/letter\/number or ASCII values int 2 or 4 Stores whole numbers, without decimals float 4 Stores fractional number, containing one or [&hellip;]<\/p>\n","protected":false},"author":42,"featured_media":214,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-212","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-personal"],"_links":{"self":[{"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/posts\/212","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/users\/42"}],"replies":[{"embeddable":true,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/comments?post=212"}],"version-history":[{"count":4,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/posts\/212\/revisions"}],"predecessor-version":[{"id":219,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/posts\/212\/revisions\/219"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/media\/214"}],"wp:attachment":[{"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/media?parent=212"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/categories?post=212"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sites.wsagames.com\/jl9u24\/wp-json\/wp\/v2\/tags?post=212"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}