例4-3一圆形游泳池如图所示,现在需在其周围建一圆形过道,并在其四周围上栅栏。栅栏价格为35元/米,过道造价为20元/平方米。过道宽度为3米,游泳池半径由键盘输入。要求编程计算并输出过道和栅栏的造价。
输入格式:
输入一个整数或小数。
输出格式:
分两行输出:在第一行中输出栅栏的造价。在第二行输出过道的造价。
输入样例:
10
输出样例:
Fencing Cost is $2858.85
Concrete Cost is $4335.4
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <iostream>
using namespace std;
int main(){
double r,cr,ar;
float pi=3.1415926;
cin>>r;
cr=35*2*pi*(r+3);
ar=((r+3)*(r+3)*pi)*20-(r*r*pi)*20;
cout<<"Fencing Cost is $"<<cr<<endl;
cout<<"Concrete Cost is $"<<ar;
return 0;
}
#include<iostream>
using namespace std;
class Test
{
private:
double r;
const double pi = 3.1415926;
public:
Test(double bj):r(bj){}
double zljg()
{
return 35*2*pi*(r+3);
}
double gdjg()
{
return (pi*(r+3)*(r+3)-pi*r*r)*20;
}
void display() {
cout << "Fencing Cost is $" << zljg() << endl;
cout << "Concrete Cost is $" << gdjg() << endl;
}
};
int main()
{
double r;
cin >> r;
Test test(r);
test.display();
return 0;
}
#include<iostream>
using namespace std;
class Test
{
private:
double r;
const double pi = 3.1415926;
public:
Test(double bj):r(bj){}
double zljg()
{
return 35*2*pi*(r+3);
}
double gdjg()
{
return (pi*(r+3)*(r+3)-pi*r*r)*20;
}
void display() {
cout << "Fencing Cost is $" << zljg() << endl;
cout << "Concrete Cost is $" << gdjg() << endl;
}
};
int main()
{
double r;
cin >> r;
Test test(r);
test.display();
return 0;
}
怎么调用gdjg()和zljg()
在C++中,成员函数需要通过对象来调用。你已经在类 Test
中定义了 gdjg()
和 zljg()
成员函数,并且在 main
函数中创建了一个 Test
对象 test
。要调用这些成员函数,可以通过这个对象来调用它们。
在你提供的代码中,gdjg()
和 zljg()
的调用已经包含在 display()
方法中,因此你不需要在 main
函数中单独调用它们。不过,如果你想在 main
函数中直接调用它们,也是可以的
zljg()
和 gdjg()
使用的是类的成员变量 r
。成员变量 r
在对象创建时通过构造函数 Test(double bj)
进行了初始化。因为成员变量 r
是类的一部分,所以类的成员函数 zljg()
和 gdjg()
可以直接访问它们。这两个函数都不需要额外的输入参数,因为它们已经有了类的成员变量 r
提供所需的值。
需要形参的情形
如果 zljg()
和 gdjg()
需要计算不同的栅栏和过道造价(例如,对于不同的半径值),那么可以将半径作为参数传递给这两个函数。这样设计的情况下,函数定义和调用方式需要更改。
#include <iostream>
#include <iomanip>
using namespace std;
class Test {
private:
const double pi = 3.1415926; // 圆周率常量
public:
// 计算栅栏造价的方法
double zljg(double r) {
return 35 * 2 * pi * (r + 3);
}
// 计算过道造价的方法
double gdjg(double r) {
return (pi * (r + 3) * (r + 3) - pi * r * r) * 20;
}
// 显示结果的方法
void display(double r) {
cout << fixed << setprecision(2);
cout << "Fencing Cost is $" << zljg(r) << endl;
cout << "Concrete Cost is $" << gdjg(r) << endl;
}
};
int main() {
double r;
cin >> r; // 从输入读取游泳池的半径
Test test; // 创建 Test 对象
test.display(r); // 调用 display 方法并传递半径参数
return 0;
}
总结
- 在当前设计中,
zljg()
和gdjg()
不需要形参,因为它们使用的是对象的成员变量r
。 - 如果希望计算不同半径的造价,可以将半径作为参数传递给这些函数,这样它们就需要形参。
这种设计选择主要取决于具体需求和设计的灵活性。