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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With