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 more decimals. Sufficient for storing 6-7 decimal digits |
double | 8 | Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits |
Using these I can use it for simple maths.
By using int when I need to store a whole number without decimals, I can store numbers such as 25, 1000, or even 210981324.
and float or double for “floating” point numbers like 9.99 or 3.14159265
int myNum = 1000;
cout << myNum;
float myNum = 5.5;
cout << myNum;
double myNum = 3.1415;
cout << myNum;
float vs double
The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.
A floating point number can also be a scientific number with an “e” to indicate the power of 10
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Max and Min
The max(x,y) function can be used top find the highest value of x and y
cout << max(5, 10);
and the min(x,y) function can be used to find the lowest value of x and y
cout << min(5, 10);
C++ <cmath> library
Other functions such as sqrt (square root), round (rounds a number) and log (natural logarithm) can be found in the <cmath> header file.
// Include the cmath library
#include <cmath>
cout << sqrt(64);
cout << round(2.7);
cout << log(2);
Building a Calculator
#include <iostream> // For input/output operations (cin, cout)
#include <limits> // For numeric_limits (handling input errors)
#include <cmath> // For mathematical functions (pow, sqrt, etc.)
using namespace std; // Allows us to use standard library names without std:: prefix
// Function to display the calculator menu
void displayMenu() {
cout << "\n=== SIMPLE CALCULATOR ===\n";
cout << "1. Addition (+)\n";
cout << "2. Subtraction (-)\n";
cout << "3. Multiplication (*)\n";
cout << "4. Division (/)\n";
cout << "5. Power (^)\n";
cout << "6. Square Root (√)\n";
cout << "7. Exit\n";
cout << "Enter your choice (1-7): ";
}
// Function to get a valid number from user
double getNumber(string prompt) {
double num;
while (true) {
cout << prompt;
cin >> num;
// Check if input failed (user entered non-numeric)
if (cin.fail()) {
cin.clear(); // Clear error flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard invalid input
cout << "Invalid input! Please enter a number.\n";
} else {
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clear input buffer
return num;
}
}
}
// Function to perform addition
double add(double a, double b) {
return a + b; // Simply return sum
}
// Function to perform subtraction
double subtract(double a, double b) {
return a - b; // Simply return difference
}
// Function to perform multiplication
double multiply(double a, double b) {
return a * b; // Simply return product
}
// Function to perform division with error checking
double divide(double a, double b) {
if (b == 0) { // Check for division by zero
cout << "Error: Division by zero is not allowed!\n";
return 0; // Return 0 as default value
}
return a / b; // Return quotient
}
// Function to calculate power
double power(double base, double exponent) {
return pow(base, exponent); // Use cmath's pow function
}
// Function to calculate square root with error checking
double squareRoot(double num) {
if (num < 0) { // Check for negative numbers
cout << "Error: Cannot calculate square root of negative number!\n";
return 0; // Return 0 as default value
}
return sqrt(num); // Use cmath's sqrt function
}
int main() {
int choice; // Variable to store user's menu choice
double num1, num2; // Variables to store operands
double result; // Variable to store calculation result
cout << "Welcome to the C++ Calculator!\n";
// Main program loop - continues until user chooses to exit
while (true) {
displayMenu(); // Show menu options
cin >> choice; // Get user's choice
// Check if menu input is valid
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid choice! Please enter a number.\n";
continue; // Skip rest of loop and start over
}
// Handle exit option
if (choice == 7) {
cout << "Thank you for using the calculator. Goodbye!\n";
break; // Exit the while loop, ending the program
}
// Process calculator operations based on user's choice
switch(choice) {
case 1: // Addition
cout << "\n--- ADDITION ---\n";
num1 = getNumber("Enter first number: ");
num2 = getNumber("Enter second number: ");
result = add(num1, num2);
cout << num1 << " + " << num2 << " = " << result << "\n";
break;
case 2: // Subtraction
cout << "\n--- SUBTRACTION ---\n";
num1 = getNumber("Enter first number: ");
num2 = getNumber("Enter second number: ");
result = subtract(num1, num2);
cout << num1 << " - " << num2 << " = " << result << "\n";
break;
case 3: // Multiplication
cout << "\n--- MULTIPLICATION ---\n";
num1 = getNumber("Enter first number: ");
num2 = getNumber("Enter second number: ");
result = multiply(num1, num2);
cout << num1 << " * " << num2 << " = " << result << "\n";
break;
case 4: // Division
cout << "\n--- DIVISION ---\n";
num1 = getNumber("Enter dividend: ");
num2 = getNumber("Enter divisor: ");
result = divide(num1, num2);
if (num2 != 0) { // Only display result if division was valid
cout << num1 << " / " << num2 << " = " << result << "\n";
}
break;
case 5: // Power
cout << "\n--- POWER ---\n";
num1 = getNumber("Enter base: ");
num2 = getNumber("Enter exponent: ");
result = power(num1, num2);
cout << num1 << " ^ " << num2 << " = " << result << "\n";
break;
case 6: // Square Root
cout << "\n--- SQUARE ROOT ---\n";
num1 = getNumber("Enter number: ");
result = squareRoot(num1);
if (num1 >= 0) { // Only display result if input was valid
cout << "√" << num1 << " = " << result << "\n";
}
break;
default: // Invalid menu choice
cout << "Invalid choice. Please select 1-7.\n";
}
cout << "\nPress Enter to continue...";
cin.get(); // Wait for user to press Enter
}
return 0; // Program ended successfully
}
Detailed Explanation
Header Files (Lines 1-3)
#include <iostream>: Includes input/output stream library for console operations#include <limits>: Providesnumeric_limitsfor handling input buffer sizes#include <cmath>: Includes mathematical functions likepow()andsqrt()
Using Namespace (Line 5)
using namespace std;: Allows direct use of standard library elements withoutstd::prefix
displayMenu() Function (Lines 8-16)
- Simple function that displays calculator options
- Uses
coutto print formatted menu to console
getNumber() Function (Lines 19-34)
- Purpose: Safely gets numeric input from user with error handling
- While loop: Continues until valid input is received
- cin.fail(): Checks if input stream failed (non-numeric input)
- cin.clear(): Clears error flags on input stream
- cin.ignore(): Discards invalid characters from input buffer
- Return: Validated number as double
Mathematical Functions (Lines 37-66)
- add(), subtract(), multiply(): Simple arithmetic operations
- divide(): Includes division by zero check
- power(): Uses
pow()from cmath library - squareRoot(): Checks for negative numbers before using
sqrt()
main() Function – Variables (Lines 69-71)
choice: Stores menu selectionnum1, num2: Store operands for calculationsresult: Stores calculation result
Main Program Loop (Lines 76-143)
- Display menu and get user choice
- Validate input using
cin.fail() - Check for exit (choice == 7)
- Switch statement: Processes different operations based on choice
- Each case:
- Shows operation title
- Gets numbers using
getNumber() - Performs calculation
- Displays result with proper formatting
- Default case: Handles invalid choices
- Pause: Waits for Enter key before continuing
Error Handling Features
- Division by zero detection
- Negative square root detection
- Invalid numeric input handling
- Invalid menu choice handling
Key Concepts:
- Functions: Modular code organization
- Input validation: Preventing crashes from bad input
- Switch statements: Clean menu handling
- Loops: Continuous operation until exit
- Error handling: Graceful error messages
- Mathematical operations: Using cmath functions
- User interface: Clear prompts and formatted output
Claude ai was used for any helps and adjustments
Code was copied and pasted from my own cLion project.
If you want to view the code:
Go here:
Then
Download this: https://drive.google.com/file/d/1BbRHlHsXpo7xhx68MiqD2pkLzGORU0bg/view?usp=drive_link
And paste it to the compiler
Then click run
Leave a Reply