-3

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.

Hasib
  • 19
  • 5

3 Answers3

2

As many have pointed out, use std::fixed and std::setprecision

#include <iostream>
#include <iomanip>
int main()
{
    float x = 22.0/7.0;

    std::cout << std::fixed << std::setprecision(25) << x;
    return 0;
}

But when you run this you will see the output is 3.1428570747375488281250000 when it should be 3.1428571428571428571428571. What gives?

Well, floats can only hold so much before having to give up and say, "Best I can do, mate." Rumour has it, this point is about 7 digits. Based on a quick count that looks about right.

So what say we try a double. They're twice the size!

#include <iostream>
#include <iomanip>
int main()
{
    double x = 22.0/7.0;

    std::cout << std::fixed << std::setprecision(25) << x;
    return 0;
}

gives us 3.1428571428571427937015414. Still not 3.1428571428571428571428571, but closer. What have we got that's bigger than double? Just tried long double. No dice on my computer. Looks like we're going to have to go looking for a good high precision floating point library.

Bummer. Well, there is one in Boost. I someday expect to see boost::kitchen_sink.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • you don't need a library , check my answer you may learn something new – Hassen Dhia Sep 28 '16 at 15:48
  • 1
    @HassenDhia Basic arithmetic isn't exactly new, but I see your point. I'm going to leave my answer here because it explains the whys and wherefores should a future questioner need to do more than just print the result. – user4581301 Sep 28 '16 at 17:05
1

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;
}
Hassen Dhia
  • 555
  • 4
  • 11
  • Look up the '*' character in format specifiers. This could help your C style example. – Thomas Matthews Sep 27 '16 at 21:53
  • I'm pretty sure this isnt what the OP is asking for. Your answer will print the value to 25 points, but it wont print the _correct_ answer to 25 points. For instance, using the OP's inputs of `n=25` and changing your printf line to `printf(ss.str(),22.0/7.0)` gives 3.1428571428571427937015414. It sounds like he wants to actually get an accurate answer for all 25 digits of precision. – Jvinniec Sep 27 '16 at 22:14
  • im really sorry i didn't read his question i was busy and read the title only – Hassen Dhia Sep 27 '16 at 22:41
  • Edited , enjoy the solution ;) – Hassen Dhia Sep 27 '16 at 23:07
  • Good solution to OP's problem. Recommend removing the the time profiling because it isn't needed to explain the solution and makes it more difficult to pick the solution out of the provided code. Also a note on `register`. A modern compiler ignores the instruction and makes up it's own mind about what goes into a register or not based on how it is going to optimize the code. Odds are pretty good that `register` will vanish from the language in the next few years and you may get a deprecation warning. – user4581301 Sep 28 '16 at 17:03
  • Thank you. We can make it more efficient by removing the inner while loop. while (precision_counter – Hasib Oct 02 '16 at 19:46
  • yeah use the optimized comented loop insted , but believe me the difference is in few nanoseconds , or millisec for huge divisions – Hassen Dhia Oct 14 '16 at 08:15
1
#include <iostream>
#include <string>
#include <sstream>

std::string f(int A, int B, int C){//A: numerator, B:denominator, C:digits after decimal point
    std::stringstream ss;
    int count = 0;

    if(A < 0){
        A = -A;
        ++count;
    }
    if(B < 0){
        B = -B;
        ++count;
    }
    if(count == 1)
        ss << '-';
    ss << A / B << '.';
    A %= B;
    A *= 10;
    count = C;
    while(count--){
        ss << A / B;
        A %= B;
        A *= 10;
    }

    return ss.str();
}

int main(void){
    std::cout << f(22, 7, 25) << std::endl;
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • In plain English, do the math long form. Recommendation: refactoring `A` and `B` to a more descriptive `numerator` and `denominator` or similar will make this much easier to read. Regardless, a much better general solution than other answers. – user4581301 Sep 28 '16 at 17:17
  • A,B and C are tailored to the representation of the OP – BLUEPIXY Sep 28 '16 at 17:37