2011-12-10 25 views
2

これはプロジェクト用に作成したコードです。C++のプログラム間違った結果

radious given:288 
x=260444. 

理由です:私はそれを実行すると、関係なく、私はradiousに置くものを数それは私に同じ答えを与えないので、その基本的なものが、私は何かを見落としている必要がありますか?

#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

それは半径でなければなりません:) – 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; 
} 

あなたはshadows the one you wantローカル変数としてRadiousを再宣言しています。関数の復帰後にその値が失われます。

+0

ありがとう!どのような愚かな間違い... :) – System

+0

@システム:コンパイラの警告レベルを上げる場合。コンパイラはこのような間違いを警告します。 –

+0

@ロキどのようにすればいいですか?私のコンパイラはdev C++ – System

2

このライン

int Radious = R; 

はちょうどあなたがクラスレベルの変数をシャドウローカル変数(関数レベル)を作成している

Radious = R; 

をお読みください。次に、Rをその変数に代入し、スコープを離れるときに破棄されます。

1

Radius変数をsetRadious関数のローカルスコープで再宣言しています。

変更:

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を削除すると、メンバー変数RadiousRが割り当てられます。

"半径" btwである必要があります。

関連する問題