Safe Division Function
C
Easy
3 views
Problem Description
Create a function that performs division but first checks for zero. If the denominator is zero, return an error code and do not write a value to the result pointer.
Official Solution
#include <stdio.h>
int safe_divide(int numerator, int denominator, float *result) {
if (denominator == 0) {
return -1; // error: division by zero
}
*result = (float)numerator / denominator;
return 0; // success
}
int main() {
int a = 10, b = 0;
float answer;
int status;
status = safe_divide(a, b, &answer);
if (status == 0) {
printf("Result = %.2fn", answer);
} else {
printf("Error: Division by zeron");
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!