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

With out using printf in c how do you do these int printF(double x, int n); // F

ID: 3817381 • Letter: W

Question

With out using printf in c how do you do these

int printF(double x, int n); // Format: fff.ffff


Outputs x as a fixed point string with n digits to the right of the decimal point. Value should be properly rounded. If n < 0, do not print the decimal point (otherwise the same as n = 0).


int printE(double x, int n); // Format: f.fffea (x = f.fff * 10^a)


Outputs x in exponential notation with exactly one non-zero digit to the left of the decimal point (unless x = 0) and n digits to the right, a lowercase ‘e’, and the exponent. If n < 0, do not print the decimal point (otherwise same as n = 0).

Explanation / Answer

PROGRAM CODE:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int printF(double x, int n)
{
int wholeNumber = trunc(x), sample, decimal;
   char output[50] = "", integer[20], dec[20];
   int number = 10;
   for(int i=1; i<n; i++)
   {
       number *= 10;
   }
   snprintf(integer, 20, "%d", wholeNumber);
   strcat(output, integer);
       double decimalPart = modf(x, &sample);
       decimalPart = decimalPart*number;
       int next_part_in_fraction = ((int)floor(decimalPart*10)) % 10;
       decimal = trunc(decimalPart);
       if(next_part_in_fraction >5)
           decimal= decimal +1;
       snprintf(dec, 20, "%d", decimal);
   if(n>0)
   {
       strcat(output, ".");
       strcat(output, dec);
   }
   puts(output);
  
}

int printE(double x, int n)
{
   char output[20], number[20], remainingNumbers[20];
   int a = 0;
   snprintf(number, 20, "%f", x);
   output[0] = number[0];
   if(n>0)
   {
       strcat(output, ".");
       int count = 1;
       for(int i=1; i<strlen(number); i++)
       {
           if(i<=n)
           {
               if(number[i] == '.')
                   continue;
               output[i+1] = number[i];
               count++;
           }
           else
               break;
       }
       strcat(output,"e");
       a = strlen(number)-1 - count;
       snprintf(remainingNumbers, 20, "%d", a);
       strcat(output,remainingNumbers );
   }
   puts(output);
  
}

int main(void) {
   printF(23.47, 2);
   printF(567.2445, 3);
   printF(555.123, 1);
   printE(514762.224234, 3);
   return 0;
}

OUTPUT:

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