0

I've written this code but it is not giving the Exact (Precise) answer. It automatically rounds up the answer. Please take a look at this and help me solve this issue. When I calculate with calculator it shows me different results and when I calculate with my program it show me different results which I think are not Exact, I want exact results. The value I am using for rad1 = 281.531 and rad2 = 118.213. See the attached image. Note: This is the first time I am asking a question online, so please ignore my mistakes.

#include <iostream>

using namespace std;

double circleArea (double);

int main()
{
    double rad1,rad2;
    double ringarea;
    cout << "Please enter the radius of Outer Circle: ";
    cin >> rad1;
    cout << "Please enter the radius of Inner Circle: ";
    cin >> rad2;
    ringarea = circleArea(rad1) - circleArea(rad2);
    cout << "The area of the Outer Circle is: " << circleArea(rad1) << endl;
    cout << "The area of the Inner Circle is: " << circleArea(rad2) << endl;
    cout << "The area of the Ring is: " << ringarea << endl;
    return 0;
}

double circleArea (double r)
{
    double pi = 3.1415926;
    return (pi * r * r);
}

Screenshot of Output

  • 1
    Where is "the attached image"? (posting images of what can be posted as text is [a bad idea](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) though) – MikeCAT Nov 15 '20 at 10:11
  • What you are asking for is impossible. There are no exact results with floating point calculations because computers don't have infinite memory (even your calculator is not exact). – john Nov 15 '20 at 10:18
  • You are complaining about precision (due to default rounding of `iostream`), but you are using a very approximate value for Pi... – prapin Nov 15 '20 at 10:18
  • 1
    If what you are really asking for is more precision (not exact precision) then try this `cout << fixed << setprecision(17);` before your other output. Use `#include ` for `setprecision`. – john Nov 15 '20 at 10:20
  • @john -- There is exact floating point math *if* all the numbers are negative powers of 2 or can be represented as sums of those numbers. Otherwise you're correct. – PaulMcKenzie Nov 15 '20 at 10:21

0 Answers0