I am writing a C program which adds two nonzero integers which are given as fractions. The integers are input as n1 d1 n2 d2. There seems to be an error when certain negative numbers are input, such as in the following combination ( 1 2 -1 2). This should state that the numbers being added are 1/2 and -1/2, and then state that the sum is 0. Instead, the program just shows a blank line and does not accept any further input. The second problem I have is that when the sentinel value is input the program is supposed to display a termination message and then end, instead it displays “floating point exception”.
int
main( void )
{
int n1;
int d1;
int n2;
int d2;
int g;
int p;
int q;
int again;
int sumn;
int sumd;
again = 1;
while ( again == 1 ) {
printf( "Please enter 4 nonzero integers representing the fractions: " );
scanf( "%d%d%d%d", &n1, &d1, &n2, &d2 );
if ( n1 == 0 && n2 == 0 && d1 == 0 && d2 == 0 ) {
again = 0;
}
else {
again = 1;
}
if ( ( n1 == 0 || n2 == 0 || d1 == 0 || d2 == 0 ) && ( n1 != 0 || n2 != 0 || d1 != 0 || d2 != 0 ) ) {
printf( "One or more of the integers is zero\n" );
again = 1;
}
else {
g = gcd( d1, d2 );
p = ( ( n1 * ( d2 / g ) ) + ( n2 * ( d1 / g ) ) );
q = ( d1 * ( d2 / g ) );
sumn = ( p / ( gcd( p, q ) ) );
sumd = ( q / ( gcd( p, q ) ) );
printf( "The fractions are: %d/%d and %d/%d\n", n1, d1, n2, d2 );
if ( sumn == sumd ) {
printf( "Their sum is: 1\n" );
}
else {
if ( sumd == 1 ) {
printf( "Their sum is: %d\n", sumn );
}
else {
printf( "Their sum is: %d/%d\n", sumn, sumd );
}
}
}
}
printf( "***** Program Terminated *****\n" );
return (EXIT_SUCCESS);
}
int gcd( int a, int b )
{
while ( a != b ) {
if ( a > b ) {
a = ( a - b );
}
else {
b = ( b - a );
}
}
return a;
}
GCD should be taken care of by providing only positive values. As mystical pointed, you should make the numbers positive. Moreover you should also check if any number coming in is not zero. So, edit the GCD function as follows:
You can now see you get correct result results for even the combination like (1 2 -1 2) or even (-1 -1 -2 -2).
And to solve the sentinel problem, edit the while loop as:
-Sandip