C Online Compiler
Example: Calculate Weight on Different Celestial Bodies in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Weight on Different Celestial Bodies #include <stdio.h> // Define gravitational accelerations for various celestial bodies (in m/s^2) #define GRAVITY_EARTH 9.81 #define GRAVITY_MOON 1.62 #define GRAVITY_MARS 3.71 #define GRAVITY_JUPITER 24.79 int main() { float mass; float gravity; float weight; int choice; // Step 1: Prompt user for mass input printf("Please enter the object's mass in kilograms (kg): "); if (scanf("%f", &mass) != 1 || mass < 0) { printf("Invalid input. Please enter a non-negative number for mass.\n"); return 1; } // Step 2: Present options for celestial bodies printf("\nSelect a celestial body to calculate weight on:\n"); printf("1. Earth (g = %.2f m/s^2)\n", GRAVITY_EARTH); printf("2. Moon (g = %.2f m/s^2)\n", GRAVITY_MOON); printf("3. Mars (g = %.2f m/s^2)\n", GRAVITY_MARS); printf("4. Jupiter (g = %.2f m/s^2)\n", GRAVITY_JUPITER); printf("Enter your choice (1-4): "); // Step 3: Read user's choice and set gravity accordingly if (scanf("%d", &choice) != 1 || choice < 1 || choice > 4) { printf("Invalid choice. Please enter a number between 1 and 4.\n"); return 1; } switch (choice) { case 1: gravity = GRAVITY_EARTH; printf("Calculating weight on Earth...\n"); break; case 2: gravity = GRAVITY_MOON; printf("Calculating weight on Moon...\n"); break; case 3: gravity = GRAVITY_MARS; printf("Calculating weight on Mars...\n"); break; case 4: gravity = GRAVITY_JUPITER; printf("Calculating weight on Jupiter...\n"); break; default: // This case should ideally not be reached due to prior validation printf("An unexpected error occurred.\n"); return 1; } // Step 4: Calculate weight using the formula W = m * g weight = mass * gravity; // Step 5: Display the calculated mass and weight for the chosen body printf("The mass of the object is: %.2f kg\n", mass); printf("The weight of the object is: %.2f N\n", weight); return 0; }
Output
Clear
ADVERTISEMENTS