这是我为一个项目创建的代码。它是基本的东西,但我一定忽略了一些东西,因为当我运行它时,无论我在 radio 上输入什么数字,它都会给我相同的答案:
radious given:288
x=260444.
这是为什么?
#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;
}
最佳答案
改变这个:
if (R > 0) //check validity of R
{
int Radious = R;
RadiousSet = true;
}
为此:
if (R > 0) //check validity of R
{
Radious = R;
RadiousSet = true;
}
您正在将 Radious
重新声明为局部变量 shadows the one you want .它的值在函数返回后丢失。
关于C++ 程序错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8459185/