Hasib Hasib - 2 months ago 6
C++ Question

How to print a number with precision given by the user in c++

How to print a number with precision given by the user. And how to print precision after decimal point up to 100 digits.

Suppose A,B,C be three numbers and take the value of three numbers from the user and I have to print the answer of A/B ( A divided by B ) to C floating points.

If A=22, B=7 , C=25, that means I have to print the result of 22/7 to 25 floating points.

3.1428571428571428571428571 , this is the answer of 22/7 , 25 digits after decimal point.

Answer

To print a float with a precision "n" you should write :

printf("%.nf"); // like printf("%.3f")

there you are a c++ full code

    #include <stdio.h>
    #include <stdlib.h>
    #include <strstream>
    #include <iostream>
    int main()
    {
        // print a float with precision '4'
        printf("%.4f",10.125f);
        // print a float with precision 'n'
        char * buffer = new char[100];
        int n;
        std::strstream ss; // like cout but outputs to a string buffer
        ss<<"%.";
        std::cout<<"Enter precision : ";
        std::cin>>n;
        ss<<n<<"f";
        printf(ss.str(),10,125); // ss.str() to get buffer content
        delete[] buffer;
     return 0;   
    }

but very simply you still can write

      std::cout << std::setprecision(n) << float_var;

EDIT : you can do you own division ! i mean you can simulate the devision of the processor and get whatever precision you want , till inifinity ! , there you are the amazing code that i wrote for my friend one time for fun :

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <chrono>
int main()
{
std::cout.sync_with_stdio(false); // accelerate output
register int x,y;
char opp;
std::cout<<"Enter x/y : ";
std::cin>>x>>opp>>y;
std::cout<<"deviding "<<x<<" by "<<y<<std::endl;
register int precision;
std::cout<<"Enter precision  : ";
std::cin>>precision;
register int precision_counter = 0;

  typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::nanoseconds ms;
typedef std::chrono::duration<float> fsec;
auto t0 = Time::now();

std::cout <<"Result = ";
std::cout<<x/y;
// check if there will be a float point result to print a point
if(x<y || x%y != 0)
 {
       std::cout<<".";
x%=y; // remove what we printed
register int counter = 0;
// print digts that are after the float point
while (precision_counter<precision )
{
     x*=10;
     while (x>=y)
     {
           x-= y;
           counter++;
     }
     std::cout<<counter;
     counter = 0;
     precision_counter++;
}

/*
optimized loop :

 while (precision_counter<precision )
{
     x*=10;
     std::cout<<x/y;
     x%=y;
     precision_counter++;
}
  **/
 }

auto t1 = Time::now();
fsec fs = t1 - t0;
std::cout<<"\n";
ms d = std::chrono::duration_cast<ms>(fs);
std::cout << fs.count() << "s\n";
std::cout << d.count() << " nanosecond\n";
 std::cout<<std::endl;
 system("pause");
return 0;
}
Comments