Today’s task is to write a program that calculates the area of a circle based on a radius value provided by the user. This challenge will introduce you to mathematical formulas, constants, and using user input to perform computations.
The formula for the area of a circle is:
Area = π × r2
Where:
To calculate the area, you’ll multiply the radius (r) by itself to get r2 (radius squared), then multiply the result by π.
Example: For r=5:
Area = 3.14159 × (52) = 3.14159 × 25 = 78.53975
Prompt the user to enter the radius of the circle. Make sure the input is converted to a numeric type (e.g., float
or double
) to handle decimal values.
math.pi
from the math
module.Math.PI
.Math.PI
.Output the calculated area to the user in a formatted way.
import math # Import the math module for math.pi
# Get the radius from the user
radius = float(input("Enter the radius of the circle: "))
# Calculate the area
area = math.pi * (radius ** 2)
# Display the result
print(f"The area of the circle with radius {radius} is: {area:.2f}")
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the radius from the user
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
// Calculate the area
double area = Math.PI * Math.pow(radius, 2);
// Display the result
System.out.printf("The area of the circle with radius %.2f is: %.2f\n", radius, area);
}
}
// Get the radius from the user
let radius = parseFloat(prompt("Enter the radius of the circle:"));
// Calculate the area
let area = Math.PI * Math.pow(radius, 2);
// Display the result
console.log(`The area of the circle with radius ${radius} is: ${area.toFixed(2)}`);
Negative Radius: Handle cases where the user enters a negative radius. You can show an error message or prompt the user to re-enter a valid value.pythonKopierenBearbeitenif radius < 0: print("Error: The radius cannot be negative.")
Zero Radius: If the radius is 0, the area should be 0.
Invalid Input: Ensure the program handles non-numeric input gracefully, prompting the user to enter a valid number.
Once you’ve successfully completed this program, try the following:
float
and double
.Now that you’ve worked with formulas and calculations, get ready for the next challenge, which will build on these skills to introduce more advanced concepts like loops or conditional branching!