使用c++编写程序:已知dat1.dat存放了一系列整型数据。 要求: 1)用dat1.dat中的前100个数据给数组int a[100]赋值,并在屏幕上输出(每行10个元素)。 2)使用函数 double isaver(int *p,int num) { } 求数组a中所有数组元素平均值。 3)把该函数放在头文件ISaver.h中以便在主函数中调用该函数。把所有小于平均值的数组元素(每行10个元素)和小于平均值的数组元素个数输出出来。(在屏幕上和数据文件d:\dat6.dat中同时输出) 题目中使用的数据文件请在附件中下载,解压后可使用。 dat1.rar 下载
时间: 2023-12-10 21:37:42 浏览: 43
以下是C++代码实现:
```cpp
#include <iostream>
#include <fstream>
#include "ISaver.h" // 头文件
using namespace std;
int main() {
ifstream fin("dat1.dat", ios::binary);
int a[100];
for (int i = 0; i < 100; i++) {
fin.read((char*) &a[i], sizeof(int));
}
fin.close();
// 输出数组a
cout << "数组a:\n";
for (int i = 0; i < 100; i++) {
cout << a[i] << " ";
if ((i + 1) % 10 == 0) {
cout << endl;
}
}
// 计算平均数
double avg = isaver(a, 100);
// 输出小于平均数的元素和个数
int count = 0;
ofstream fout("d:\\dat6.dat", ios::binary);
fout.write((char*) &count, sizeof(int)); // 先写入个数,最后再修改
cout << "\n小于平均数的元素:\n";
for (int i = 0; i < 100; i++) {
if (a[i] < avg) {
count++;
cout << a[i] << " ";
fout.write((char*) &a[i], sizeof(int));
if (count % 10 == 0) {
cout << endl;
}
}
}
fout.seekp(0); // 回到文件开头
fout.write((char*) &count, sizeof(int)); // 修改个数
fout.close();
cout << "\n小于平均数的元素个数为:" << count << endl;
return 0;
}
```
ISaver.h头文件内容如下:
```cpp
#ifndef ISaver_h
#define ISaver_h
double isaver(int *p, int num) {
double sum = 0;
for (int i = 0; i < num; i++) {
sum += p[i];
}
return sum / num;
}
#endif /* ISaver_h */
```
注意,需要将ISaver.h和main.cpp放在同一目录下,并且需要在编译时加上头文件的路径,例如:
```
g++ -I. main.cpp -o main
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)