C Online Compiler
Example: Calculate Mass and Weight from Density and Volume in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Mass and Weight from Density and Volume #include <stdio.h> #define GRAVITY_EARTH 9.81 // Acceleration due to gravity on Earth in m/s^2 int main() { float density; // Density in kg/m^3 float volume; // Volume in m^3 float mass; float weight; // Step 1: Prompt user for density input printf("Please enter the object's density in kilograms per cubic meter (kg/m^3): "); if (scanf("%f", &density) != 1 || density < 0) { printf("Invalid input. Please enter a non-negative number for density.\n"); return 1; } // Step 2: Prompt user for volume input printf("Please enter the object's volume in cubic meters (m^3): "); if (scanf("%f", &volume) != 1 || volume < 0) { printf("Invalid input. Please enter a non-negative number for volume.\n"); return 1; } // Step 3: Calculate mass using the formula m = rho * V mass = density * volume; // Step 4: Calculate weight using the formula W = m * g weight = mass * GRAVITY_EARTH; // Step 5: Display the calculated density, volume, mass, and weight printf("\nObject Properties:\n"); printf(" Density: %.2f kg/m^3\n", density); printf(" Volume: %.2f m^3\n", volume); printf(" Mass: %.2f kg\n", mass); printf(" Weight on Earth: %.2f N\n", weight); return 0; }
Output
Clear
ADVERTISEMENTS