#include <stdio.h>
#include <stdbool.h>
// Define PI safely for cross-platform compatibility if not already defined
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Structure to hold all calculated circle metrics
typedef struct {
double diameter;
double circumference;
double area;
} CircleMetrics;
/**
* @brief Calculates the diameter, circumference, and area of a circle.
* @param radius The radius of the circle (must be non-negative).
* @param result Pointer to a CircleMetrics struct to store the results.
* @return true if calculation is successful, false if the radius is invalid.
*/
bool calculate_circle_metrics(double radius, CircleMetrics *result) {
// Guard clause: radius cannot be negative and pointer must not be null
if (radius < 0.0 || result == NULL) {
return false;
}
// Perform calculations
result->diameter = 2.0 * radius;
result->circumference = 2.0 * M_PI * radius;
// Multiplication (radius * radius) is more efficient than pow(radius, 2)
result->area = M_PI * (radius * radius);
return true;
}
int main(void) {
double radius = 3.0;
CircleMetrics metrics;
// Call the function and handle the success/failure status
if (calculate_circle_metrics(radius, &metrics)) {
printf("Radius: %.2f\n", radius);
printf("Diameter: %.2f\n", metrics.diameter);
printf("Circumference: %.2f\n", metrics.circumference);
printf("Area: %.2f\n", metrics.area);
} else {
fprintf(stderr, "Error: Radius cannot be negative.\n");
return 1;
}
}
/*
run:
Radius: 3.00
Diameter: 6.00
Circumference: 18.85
Area: 28.27
*/