求圆的面积

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:

885580-20160505162758247-1428444418.jpg

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值