Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ program-wrong results

Tags:

c++

This is the code I created for a project. Its basic stuff but I must have overlooked something because when I run it, no matter what number I put on the radious it gives me the same answer:

radious given:288  
x=260444.

why is that?

#include <iostream>
#include <stdlib.h>
#include <math.h>
#define pi 3.14

using std::cout;
using std::cin;
using std::endl;


class Circle 
{
private:          
    int Radious;
public:
    bool setRadious(int R);
    int getRadious(){return Radious;}
    double getx();
};


bool Circle::setRadious(int R)
{   
    bool RadiousSet = false;

    if (R > 0) //check validity of R
    {
        int Radious = R;
        RadiousSet = true;
    }     
    return RadiousSet;
}

//x = pi *R^2
double Circle::getx()
{
    return  pi*pow(Radious,2);
}

// -----------------------------

int main()
{
    int R=0;
    bool rslt;

    Circle myCircle;  


    cout<<"Give Radious: ";
    cin>>R;
    rslt = myCircle.setRadious(R);

    if(rslt == true) 
    {
        cout << "Radious given: " <<myCircle.getRadious();
        cout<<"x: "<<myCircle.getx()<<endl;
    }
    else
        cout<<"Radious must be greater than zero"<<endl;

    system("pause");
    return 0;

}
like image 387
System Avatar asked Jun 29 '26 03:06

System


2 Answers

Change this:

if (R > 0) //check validity of R
{
    int Radious = R;
    RadiousSet = true;
} 

to this:

if (R > 0) //check validity of R
{
    Radious = R;
    RadiousSet = true;
} 

You are redeclaring Radious as a local variable which shadows the one you want. Its value is lost after the function returns.

like image 117
Mysticial Avatar answered Jul 01 '26 17:07

Mysticial


bool Circle::setRadious(int R)
{   
 bool RadiousSet = false;

  if (R > 0) //check validity of R
  {
     int Radious = R;  // <== problematic line
     RadiousSet = true;
  }     
    return RadiousSet;
}

You create and assign a local Radious. Remove the int in front of it, that will cause it to assign R to the member variable Radious.

It should be "Radius" btw.

like image 45
Xeo Avatar answered Jul 01 '26 19:07

Xeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!