2011-12-10 58 views
2

这是我为一个项目创建的代码。它的基本的东西,但我一定是忽略了一些东西,因为当我运行它,无论我穿什么号码的radious它给了我同样的答案:C++程序错误结果

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; 

} 
+3

它应该是半径不radious :) – Templar

+2

是的,我知道,但教授写道它,我们不得不修改他的代码,使其工作.. :) – System

回答

7

更改此:

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。它的值在函数返回后丢失。

+0

谢谢!多么愚蠢的错误...... :) – System

+0

@System:如果你打开你的编译器的警告级别。编译器会警告你这样的错误。 –

+0

@Loki我该怎么做?我的编译器是开发C++ – System

2

此行

int Radious = R; 

应该只是读

Radious = R; 

您是创造出阴影的类级变量局部变量(函数级别)。然后,您将R分配给该变量,该变量在离开作用域时被销毁。

1

您将在setRadious函数的本地范围内重新声明您的Radius变量。

变化:

int Radious = R; 

到:

Radious = R; 

C++允许你在不同范围内声明的同名变量。因为你在这个方法中再次声明它,所以它设置本地版本并且不以任何方式影响成员变量。

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

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

您创建并分配本地Radious。删除前面的int,这会导致它将R分配给成员变量Radious

它应该是“半径”顺便说一句。