求圆的面积

requirements:

  • Create a program that asks for the radius of a circle and prints the area of that circle .
  • Use cin and cout .
  • The whole program should be divided into two source files(cpp) .
  • Hand in the source files and the head files which you create .

All files have been pushed to github. Wanna see files,click here


First of all, I create two source files,"dataio.cpp", which is for data input and output and "calculate.cpp" , which is for calculating,together with a head file, "calculate.h".
Second, in the head file, I define the value of "pi" and delclare a function, "calculate",which is used to calculate the area of the circle, as well as a variable, "area".
And then in the "calculate.cpp" file, I write the formula of calculating a circle's area and return the value of "area".
Last, I write the main function to realize data input and output in the "dataio.cpp" file.


The following is my code:

calculate.h

#define pi 3.14

double  area;
double calculate(double r);

calculate.cpp

#include"area.h"

double calculate(double r)
{
    area =pi*r*r;

    return area;
}

dataio.cpp

#include"area.h"
#include<iostream>
using namespace std;

int main()
{
    double radius;
    double square;

    cout << "Please enter radius of the circle:" << endl;
    cout << "radius=";
    cin >> radius;

    square = calculate(radius);

    cout << "area=" << square << endl;

    return 0;
}

However, when I try to compile, there are two errors:

It means the variable "area" has been defined twice. The first time is in the head file and I make it twice after including the head file in the cpp file. So, in order to solve this problem, there are two ways.
The first one is to declare the variable "area" in the "calculate.cpp" file instead of in the "calculate.h" file. Like this :

calculate.h

#define pi 3.14

double calculate(double r);

calculate.cpp

#include"area.h"

double calculate(double r)
{
    double area;
    area =pi*r*r;

    return area;
}

And the other one is to add "static" when you declare the variable "area". Just like the following.

calculate.h

#define pi 3.14

double static area;
double calculate(double r);

calculate.cpp

#include"area.h"

double calculate(double r)
{
    area =pi*r*r;

    return area;
}

And after this, you can build it successfully when compile it.



原文地址:https://www.cnblogs.com/jiuweilinghu/p/5462448.html