Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that inputs a positive real (floating point) number, and outputs

ID: 3621197 • Letter: W

Question

Write a program that inputs a positive real (floating point) number, and outputs the fraction that is closest to it among all fractions whose denominator is at most 100. If several such fractions are equally close to the input, output the one with lowest denominator. For example, among fractions with denominator 100, the closest to 0:751 are 3=4, 6=8, . . . , 75=100. The program outputs 3=4 as it has the smallest denominator among them. Print the output fraction as n/d, representing the numerator and denominator. If the denominator is 1, print just the numerator.
The error is the dierence between the output fraction and the input. Print the error to five decimal points.
Some sample runs are shown below.
(~)$ a.out
Nonnegative real number: .751
Closest approximation = 3/4, Error = -0.00100
(~)$ a.out
Nonnegative real number: 42.7488
Closest approximation = 171/4, Error = 0.00120
(~)$ a.out
Nonnegative real number: 0.0049
Closest approximation = 0, Error = -0.00490
(~)$ a.out
Nonnegative real number: 102
Closest approximation = 102, Error = 0.00000
(~)$ a.out
Nonnegative real number: 0.123456
Closest approximation = 10/81, Error = 0.00000

Explanation / Answer

please rate - thanks

#include <stdio.h>
#include <conio.h>
int main()
{float num;
int d,closestd=0;
float closestn=0,diff,fract=0,n,closestdiff=100, dn,cfac=1,fac;
printf("Nonnegative real number: ");
scanf("%f",&num);
n=0;
while(fract<=num)
   {for(d=1;d<=100;d++)
      {dn=(float)d;
      fract=n/dn;
      diff=fract-num;
      fac=1;
      if(diff<0)
          fac=-1;
      if(diff*fac<closestdiff*cfac)
          {closestn=n;
          closestd=d;
          closestdiff=diff;
          cfac=fac;
          }
       }
     n++;
     }
if(closestd==1)
      printf("Closest approximation = %d Error = %.5f ",(int)closestn,closestdiff);    
else
   printf("Closest approximation = %d/%d Error = %.5f ",(int)closestn,closestd,closestdiff);
         
         
getch();
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote