0

I was doing a program which first takes 2 numbers (with float datatype) from the user and then ask the user about up-to what digit he want's to get the number divided and finally divides it up-to that number and 'cout<<' it. It compiled but din't worked up-to the mark when I calculated 22/7 which is an irrational no. up-to 100 digits it just calculated up-to 30 or 40 digits and then rest of was filled with zeros. Something like this: 3.1428570747375488281250000000000000000000000000000000000000000000000000000000000000000000000000000000

Here is my code:

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
    system("clear");
    float y;
    int z;
    float x;
    float a;
    cout << "\nHello User\n";
    cout << "\nEnter first num to be divided: ";
    cin >> x;
    cout << "\nCool!! Now enter the 2nd number: \n";
    cin >> y;
    cout << "\Exelent!! Enter the place upto which u wanna caculate: ";
    cin >> z;
    a = x / y;
    cout << fixed << showpoint;
    cout << setprecision(z);
    cout << "Calculating......\n" << a << endl;
    return 0;
}
Hamza Anis
  • 2,475
  • 1
  • 26
  • 36
Shivam Jha
  • 182
  • 3
  • 17
  • All numbers with 6 or fewer significant decimal digits can be converted to an IEEE 754 floating-point value without loss of precision. Read up on IEEE floating-point types. – Erik Alapää Feb 17 '17 at 09:45
  • 1
    22/7 is definitely not an irrational number. – molbdnilo Feb 17 '17 at 10:07
  • oh i mean PI @molbdnilo – Shivam Jha Feb 17 '17 at 10:28
  • @ErikAlapää Could you please point me to some such documents?? – Shivam Jha Aug 22 '17 at 17:25
  • @ShivamProgramer> If you really want to understand numerical computing, the best is probably to utilize books from scientific computing. This could be a good start, I used a graduate-level book from these authors a long time ago: https://www.amazon.co.uk/Numerical-Mathematics-Computing-Kincaid-Hardcover/dp/B00OL3UU8Y/ref=sr_1_5?ie=UTF8&qid=1503496021&sr=8-5&keywords=cheney+kincaid – Erik Alapää Aug 23 '17 at 13:51

1 Answers1

4

Floating point types have certain precision. You don't get exact results when operating on floats (or doubles). Now to get a better precision use double instead of float (See this post for more details).

You could #include <limits>, remove the step that gets the precision from input and change your code to:

std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);

to display the result with maximum precision for the type you use.

Community
  • 1
  • 1
mpiatek
  • 1,313
  • 15
  • 16