Hey guys, I've got the program to compile correctly, but every time I execute, it gives me the line says "Floating point exception"? Maybe my logic isn't correct or I code somewhere wrong?
*EDIT: Well, I see the problem is the denominator can't be zero, and I correct that...and it runs now...
But the output is not correct because it doesn't choose the smallest denomintor
The programming I'm trying to do is to let the user input a nonnegative real number,
and output a fraction the closest to the input, and print out the error also.
[Error is the difference between input and output]
The denominator has to be <= 100, and it also prints out the smallest denominator, like 0.751 are 3/4, 6/8,... 75/100, but it chooses 3/4 to print out...
For example: My input is 0.751 -> printout 3/4, error = -00.100
another example: input is 42.7488 -> printout 171/4, error = 0.00120
Here's my code:
Code:
#include <stdio.h>
int main() {
//Define data types
int d, n, num, lown, lowd;
double dec, error_sq, sm_err=1, sm_err_sq;
//Print this line on screen
printf("Nonnegative real number: ");
//Scan user input
scanf("%d.%lf", &num, &dec);
//Using for loop, create "d"inomirator and "n"umerator part
//to find the closest approx.
for(d=1; d<=100; d++){
for(n=0; n<=100; n++){
//In order to compare the the error
//I have to square them both too, to make it both in positive values
//Then compare them two
sm_err_sq = sm_err * sm_err;
error_sq = (dec - n/d)*(dec - n/d);
//Using IF condition to sort the smallest error each time looping
if (error_sq<sm_err_sq){
lown = n;
lowd = d;
sm_err = dec - n/d;
}
}
}
//Print the desire value
printf("Closest approximation = %d/%d, Error = %lf\n", num*d+n, d, sm_err);
return 0;
}
Thanks for helping out. =]