P
pereges
Hi, I have written a small function that can (I think) deal with
overflow/underflow while adding integers and divide by zero problem.
Can some one please tell me if I have done it correctly ? Would it be
safe to extend it to double precision floating point numbers since we
know that there is always some margin for error while adding floating
point numbers ? What other functions should I look to implement for my
project ?
#include <stdio.h>
#include <limits.h>
int add_chk(int a, int b)
{
if (b > 0)
{
if (a > INT_MAX - b)
{
fprintf(stderr, "Overflow error\n");
return (INT_MAX);
}
}
if (b < 0)
{
if (a < INT_MIN - b)
{
fprintf(stderr, "Underflow error\n");
return (INT_MIN);
}
}
return (a + b);
}
int div_chk(int a, int b)
{
if (b == 0)
{
fprintf(stderr, "Division by zero attempted\n");
return (INT_MAX);
}
return (a/b);
}
int main(void)
{
int i;
int x, y;
clrscr();
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
}
if ((x < INT_MAX && x > INT_MIN) && ( y < INT_MAX && y >
INT_MIN))
{
i = add_chk(x, y);
printf("Sum: %d\n", i);
i = div_chk(x, y);
printf("Div: %d\n", i);
}
else
{
fprintf(stderr, "Values entered are out of range\n");
return (1);
}
return (0);
}
overflow/underflow while adding integers and divide by zero problem.
Can some one please tell me if I have done it correctly ? Would it be
safe to extend it to double precision floating point numbers since we
know that there is always some margin for error while adding floating
point numbers ? What other functions should I look to implement for my
project ?
#include <stdio.h>
#include <limits.h>
int add_chk(int a, int b)
{
if (b > 0)
{
if (a > INT_MAX - b)
{
fprintf(stderr, "Overflow error\n");
return (INT_MAX);
}
}
if (b < 0)
{
if (a < INT_MIN - b)
{
fprintf(stderr, "Underflow error\n");
return (INT_MIN);
}
}
return (a + b);
}
int div_chk(int a, int b)
{
if (b == 0)
{
fprintf(stderr, "Division by zero attempted\n");
return (INT_MAX);
}
return (a/b);
}
int main(void)
{
int i;
int x, y;
clrscr();
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
}
if ((x < INT_MAX && x > INT_MIN) && ( y < INT_MAX && y >
INT_MIN))
{
i = add_chk(x, y);
printf("Sum: %d\n", i);
i = div_chk(x, y);
printf("Div: %d\n", i);
}
else
{
fprintf(stderr, "Values entered are out of range\n");
return (1);
}
return (0);
}