Please provide me the logic to print the result using PRINTF [closed]

In order to print decimals (easily), you need floating point:

printf("%10.6f", static_cast<double>(1) / 3);

If one of the arguments to division is floating point, the compiler will promote the expression to floating point.

Integral or scalar division will lose decimals.

You are always welcome to write your own division function.

Edit 1: Shifting
You don’t need to use the pow function (especially since it’s floating point).

Use a loop, in the loop multiply your divisor by 10 each time.

double result = (double) scalar / value;
int divisor = 10;
int i;
for (i = 0; i < NUMBER_OF_DECIMALS; ++)
{
  // Isolate a digit using math.
  // print the digit
  divisor += 10;
}

The math part is left as an exercise for the OP.

Leave a Comment