0

私はC++の学習を始めたばかりで、円の面積を見つけるためのプログラムを作成しようとしています. プログラムを作成しましたが、コンパイルしようとすると、2 つのエラー メッセージが表示されます。1 つ目は次のとおりです。

areaofcircle.cpp:9:14: error: expected unqualified-id before numeric constant

2番目は次のとおりです。

areaofcircle.cpp:18:5: error: 'area' was not declared in this scope

私は何をすべきか?写真を投稿したいのですが、私は新しいユーザーなので投稿できません。

#include <iostream> 
using namespace std; 
#define pi 3.1415926535897932384626433832795 
int main() 
{
    // Create three float variable values: r, pi, area 
    float r, pi, area; 
    cout << "This program computes the area of a circle." << endl; 

    // Prompt user to enter the radius of the circle, read input value into variable r 
    cout << "Enter the radius of the circle " << endl; 
    cin >> r; 

    // Square r and then multiply by pi area = r * r * pi; 
    cout << "The area is " << area << "." << endl; 
}
4

3 に答える 3

2

問題は比較的単純です。下記参照。

#define pi 3.1415926535897932384626433832795 
int main() 
{
    // Create three float variable values: r, pi, area 
    float r, pi, area; 
...

にマクロ展開を使用していることに注意してくださいpipiこれにより、宣言内の変数名が text に置き換えられます3.1415926535897932384626433832795。これにより、次のエラーが発生します。

エラー: 数値定数の前に unqualified-id が必要です

さて、これによりそのステートメントでの解析が失敗したため、area宣言されなくなります(後であるためpi)。その結果、次のエラーも表示されます。

エラー: 'area' はこのスコープで宣言されていません

pi実際にはどちらも割り当てないことに注意してくださいarea... 最初にそれを行う必要があります。

一般的な経験則として、C++ では定数にマクロを使用しないでください。

#include <iostream>
#include <cmath>

int main() {
  using std::cin;
  using std::cout;
  using std::endl;
  using std::atan;

  cout << "This program computes the area of a circle." << endl;

  cout << "Enter the radius of the circle " << endl;
  float r;
  cin >> r;

  float pi = acos(-1.0f);
  float area = 2 * pi * r;
  cout << "The area is " << area << '.' << endl;

  return 0;
}
于 2012-09-02T00:32:45.243 に答える
0

正常にビルドおよび動作する変更されたコード:

///--------------------------------------------------------------------------------------------------!
// file:    Area.cpp
//
// summary: console program for SO

#include <iostream> 

using namespace std; 

const double PI = 3.1415926535897932384626433832795;


int main() 
{
    // Create three float variable values: r, pi, area 
    double r, area; 
    cout << "This program computes the area of a circle." << endl; 

    // Prompt user to enter the radius of the circle, read input value into variable r 
    cout << "Enter the radius of the circle " << endl; 
    cin >> r; 

    // Square r and then multiply by pi area = r * r * pi; 
    area = PI*r*r;
    cout << "The area is " << area << "." << endl;

    return 0;
}
于 2012-09-27T19:15:21.093 に答える
0

手始めに、実際には「area」に何も割り当てないため、未定義のままになります(事実上乱数が含まれます)。area = r * r * pi;最後のcoutの前に行を追加してみてください。float piまた、上部のと衝突するため、変数リストからを削除する必要があります#define pi。後で、あなたがそれについて学ぶとき、あなたは#include <math>あなたがそれを自分でする必要がないようにあなたが中に定数を見つけるかもしれません。M_PI

于 2012-09-02T00:37:16.120 に答える