0
#include <iostream>
#include <math.h>

using namespace std;

class circle
{
public:
    circle();
    circle(double radius);
    double circlerad(void);
    double area(void);
    double circumference(void);

private:
    double rad;

};

circle::circle()
{
    double rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    double rad = radius;
}

double circle::circlerad(void)
{
    return rad;
}

double circle::area(void)
{
    double res;

    res = rad * rad * 3.14;

    return res;
}

double circle::circumference(void)
{
    return (double) rad * 2 * 3.14;
}

double radius(int x1, int y1, int x2, int y2)
{
    double rad = 0;

    double xm, ym;

    xm = (double)(x1 + x2) / 2;
    ym = (double)(y1 + y2) / 2;

    rad = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));

    return rad;
}

int main(void)
{
    double rad;
    int x1, y1;
    int x2, y2;

    cout << "x1 : ";
    cin >> x1;
    cout << "y1 : ";
    cin >> y1;
    cout << "x2 : ";
    cin >> x2;
    cout << "y2 : ";
    cin >> y2;

    *circle one((double)radius(x1, y1, x2, y2));*

    cout << fixed << one.area() << endl;
    //cout << fixed << one.circumference() << endl;

    return 0;
}

this is my code to calculate circle area and circumference.

But the problem is that when I initialize circle one, regardless of radius(x1, y1, x2, y2) value,

it always initialize to -9.2559631349317831e+061.

3
  • You forgot to check whether your input operations succeed, so your program essentially has undefined behaviour.
    – Kerrek SB
    Mar 8, 2014 at 17:25
  • ym and xm are not used, make sure you cast them to doubles BEFORE you work with them.
    – Alec Teal
    Mar 8, 2014 at 17:26
  • The proper way to initialize members with a parameter is a constructor initializer list. Any good book will cover that early on in classes.
    – chris
    Mar 8, 2014 at 17:27

2 Answers 2

2

You don't initialise circle::rad here (instead you use local variable rad):

circle::circle()
{
    double rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    double rad = radius;
}

you should do something like:

circle::circle(): rad(0)
{
}

circle::circle(double radius): rad(radius)
{
}
2
  • You are expecting the OP to run before they can walk.
    – TonyK
    Mar 8, 2014 at 17:32
  • @TonyK, I don't think assigning to the members to "initialize" them should even be taught before the list.
    – chris
    Mar 8, 2014 at 17:41
1

double rad declares a local variable, which is not the same as the class member rad. The simplest fix:

circle::circle()
{
    rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    rad = radius;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.