C++ 程序错误的结果

标签 c++

这是我为一个项目创建的代码。它是基本的东西,但我一定忽略了一些东西,因为当我运行它时,无论我在 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/

相关文章:

c++ - 编码练习 : return by value or by reference in Matrix multiplication?

c++ - 不同的默认按钮设计行为

c++ - c++ 中是否有用于表示以毫秒为单位的时间的类?

c++ - 为 Windows 集成 QML 和 map /定位技术

c++ - vector::operator[] 开销

c++ - 具有静态变量的递归函数

c++ - 如何在 C++ 中为数组重载运算符<<?

c++ - 静态变量与模板类的冲突声明

c++ - 在 C++ dll 中存储状态

c++ - 运算符重载 C++ 放置