Matt Bettinson
Matt Bettinson

Reputation: 531

Why does the area come back as 0?

Here's the code.

int a;
int pi = 3.14;
int area;
int main()
{
    cout << "Input the radius of the circle ";
    cin >> a;

    a *= a *= pi >> area;

    cout << "The area is " << area;


}

Upvotes: 6

Views: 1771

Answers (8)

CodesInChaos
CodesInChaos

Reputation: 108790

Your code doesn't make any sense.

pi(and all your other variables) need to be double or float,... not int. An int can only contain an integral number. And pi is obviously not integral.

a *= a *= pi >> area; should be area = a * a * pi;

>> is a bitshift, not an assignment to the right side
*= is multiply assign and not just multiply. i.e. it is similar to left=left*right

Upvotes: 6

Alex
Alex

Reputation: 2372

The >> operator when used with numbers is right shift, not assignment. You want something like

area = a * a * pi;

Update

You also need to use a floating point type or your answer won't be what you expect.

float a;
float pi = 3.14f;
float area;

Upvotes: 13

Pudgeball
Pudgeball

Reputation: 814

The area of a circle is pi * r * r therefore you would want to do;

a = a * a * pi

Hope that helps

and they all would need to be floats.

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

int pi = 3.14;

Wrong datatype. Assigning double value to int? That's wrong.

Write this:

double pi = 3.14;

And likewise, change other datatypes to double as well.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Your code doesn't do what I think you wanted it to do. You don't assign to variables with >>; that is only for stream extraction (and bitshifting).

Also, a *= a *= pi probably doesn't do what you think it does.

Also, you want floating-point values, not int. An "int" pi is just 3.

Also, you should have error checking on your stream extraction!

Try:

int main()
{
    const float pi = 3.14;
    float a;

    cout << "Input the radius of the circle ";
    if (!(cin >> a)) {
         cout << "Invalid radius!";
         return 1;
    }

    float area = (a * a * pi);

    cout << "The area is " << area;
}

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67195

All your variables are declared as int, which simply drops any fractional portion assigned to it. To work with floating-point values, use double instead.

Also, your equation in almost incomprehensible. Not sure what you're trying to do there.

Upvotes: 1

Maxpm
Maxpm

Reputation: 25571

Because you're using int, or integer, for all your variables. You want to use doubles or even floats. (doubles are more precise).

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263118

I don't have enough patience to decipher your strange code. How about just area = a * a * pi?

Upvotes: 7

Related Questions