用c++
时间: 2023-07-01 12:24:08 浏览: 48
好的,以下是用 C++ 实现的代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class FileOpenException : public exception {
public:
const char* what() const noexcept override {
return "无法打开文件!";
}
};
double calculate_average(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
throw FileOpenException();
}
vector<int> numbers;
int number;
while (file >> number) {
numbers.push_back(number);
}
if (numbers.empty()) {
return 0.0;
}
int sum = 0;
for (int number : numbers) {
sum += number;
}
return static_cast<double>(sum) / numbers.size();
}
int main() {
string filename;
cout << "请输入文件名:";
cin >> filename;
try {
double average = calculate_average(filename);
cout << "平均值为:" << average << endl;
} catch (const FileOpenException& e) {
cerr << e.what() << endl;
}
return 0;
}
```
与 Python 版本相似,我们先定义了一个名为 `FileOpenException` 的自定义异常类。接着,定义了一个名为 `calculate_average` 的函数,该函数接受一个文件名作为参数,并返回该文件中整数的平均值。在 `calculate_average` 函数中,我们使用 `ifstream` 类来打开文件并读取整数,并使用 `vector` 类来存储读取到的整数。如果文件不存在或无法打开,我们就会抛出一个 `FileOpenException` 异常。
在主函数中,我们首先要求用户输入文件名,然后调用 `calculate_average` 函数来计算整数的平均值。如果在计算平均值的过程中出现了文件打开异常,我们就会捕获该异常并输出错误信息。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)