C++ Online Compiler
Example: Mass and Weight Calculator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Mass and Weight Calculator #include <iostream> // For input/output operations #include <iomanip> // For setting output precision using namespace std; int main() { // Step 1: Declare variables for mass, weight, and gravitational acceleration double mass_kg; double weight_newtons; const double GRAVITY_EARTH = 9.80665; // Standard gravity on Earth in m/s^2 // Step 2: Prompt the user to enter their mass cout << "Welcome to the Mass and Weight Calculator!" << endl; cout << "------------------------------------------" << endl; cout << "Please enter your mass in kilograms (kg): "; cin >> mass_kg; // Step 3: Validate input if (mass_kg < 0) { cout << "Error: Mass cannot be negative. Please enter a valid mass." << endl; return 1; // Indicate an error } // Step 4: Calculate the weight using the formula W = m * g weight_newtons = mass_kg * GRAVITY_EARTH; // Step 5: Display the results cout << fixed << setprecision(2); // Set output to 2 decimal places cout << "\n--- Calculation Results ---" << endl; cout << "Your mass is: " << mass_kg << " kg" << endl; cout << "Gravitational acceleration (Earth): " << GRAVITY_EARTH << " m/s^2" << endl; cout << "Your weight on Earth is: " << weight_newtons << " Newtons (N)" << endl; cout << "---------------------------\n" << endl; return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS