编写一个计算以a,b为边长的矩形面积的函数:float s2a(float a, float b ),放在主函数后边,然后再编写主函数,实现键盘输入n个矩形的长和宽,通过调用s2a函数,计算并分别输出这n个矩形面积(结果保留小数点后2位)。
时间: 2024-11-13 10:20:48 浏览: 44
你可以按照下面的方式编写这个程序:
首先,在头文件中声明`s2a`函数,因为我们在主函数之前定义它:
```cpp
#include <iostream>
#include <iomanip>
// 定义计算矩形面积的函数
float s2a(float a, float b) {
return a * b;
}
int main() {
// 主函数开始
int n;
std::cout << "请输入您想要计算的矩形数量: ";
std::cin >> n;
// 存储矩形的长和宽,并计算面积
for (int i = 0; i < n; ++i) {
float length, width;
std::cout << "请输入第" << i+1 << "个矩形的长度: ";
std::cin >> length;
std::cout << "请输入第" << i+1 << "个矩形的宽度: ";
std::cin >> width;
// 计算并输出面积,保留两位小数
float area = s2a(length, width);
std::cout << "第" << i+1 << "个矩形的面积为: " << std::fixed << std::setprecision(2) << area << "\n";
}
return 0;
}
```
在这个程序中,我们首先获取用户想要计算的矩形数量`n`。然后,对于每一个矩形,我们读取它的长和宽,调用`s2a`函数计算面积,然后输出结果,保留两位小数。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)