To find the maximum of three numbers a, b, and c in C, you can implement a helper function that uses conditional statements to compare each pair of values step by step. This approach is straightforward and doesn’t require additional libraries beyond standard input/output.
Approach
- Read Inputs: Capture three floating-point numbers from the user.
- Helper Function: Create a function max_three that compares two pairs of numbers:
- First, compare a and b to determine the larger of the two.
- Then, compare this intermediate result with c to find the overall maximum.
- Output Result: Print the maximum value along with the original inputs for clarity.
This method ensures readability and reusability of the code, allowing easy extension or modification if needed in the future.
Solution Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> float max_three(float x, float y, float z) { // Compare x and y first float max_xy = (x > y) ? x : y; // Now compare the result with z return (max_xy > z) ? max_xy : z; } int main() { float a, b, c; printf(“Enter three numbers: “); scanf(“%f %f %f”, &a, &b, &c); float maximum = max_three(a, b, c); printf(“The maximum of %.2f, %.2f, and %.2f is %.2f\n”, a, b, c, maximum); return 0; } |
Explanation
- Reading Inputs: The program reads three floating-point numbers using scanf.
- Helper Function max_three:
- Compares the first two numbers ( x and y) to find the larger one.
- Compares this intermediate maximum with the third number ( z) to determine the overall largest value.
- Output: The result is printed with two decimal places for precision, clearly showing which of the three input values was the largest.
This approach efficiently handles both integer and floating-point inputs and correctly processes all possible combinations, including when some or all values are equal.