#include <iostream>
#include <fstream>
#include <string>
#define MAX_MAP 64
using namespace std;
bool isPeak(const double grid[MAX_MAP][MAX_MAP], int r, int c);
bool isValley(const double grid[MAX_MAP][MAX_MAP], int r, int c);
void peakValleyPoint(int nrows, int ncols, const double map[MAX_MAP][MAX_MAP]);
void extremes(const double grid[MAX_MAP][MAX_MAP], int row, int col);
int main(void) {
int nrows, ncols;
double map[MAX_MAP][MAX_MAP];//数组的定义不能使用变量,定义一个比地图大的二维数组。
string filename;
ifstream file;
cout << "请输入文件名:" << endl;
cin >> filename;
file.open(filename.c_str());//打开文件
//判断文件打开是否失败,失败返回1
if (file.fail()) {
cout << "打开输入文件出错!" << endl;
system("pause");
exit(1);//程序错误异常退出
}
file >> nrows >> ncols;//从文件里输入行数列数
//判断文件中的数组是否能存储到
if (nrows > MAX_MAP || ncols > MAX_MAP) {
cout << "文件数据太大,无法写入!" << endl;
system("pause");
exit(1);
}
//从文件读取数据到二维数组
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
file >> map[i][j];
}
}
peakValleyPoint(nrows, ncols, map);//打印峰值点和谷点
extremes(map, nrows, ncols);
system("pause");
//关闭文件
file.close();
return 0;
}
//峰值点判断
bool isPeak(const double grid[MAX_MAP][MAX_MAP], int r, int c) {
if ((grid[r][c] > grid[r - 1][c]) &&
(grid[r][c] > grid[r + 1][c]) &&
(grid[r][c] > grid[r][c + 1]) &&
(grid[r][c] > grid[r][c - 1]) &&
(grid[r][c] > grid[r - 1][c - 1])&&
(grid[r][c] > grid[r - 1][c + 1])&&
(grid[r][c] > grid[r + 1][c - 1])&&
(grid[r][c] > grid[r + 1][c + 1])) {
return true;
}
else {
return false;
}
}
//谷值点判断
bool isValley(const double grid[MAX_MAP][MAX_MAP], int r, int c) {
if ((grid[r][c] < grid[r - 1][c]) &&
(grid[r][c] < grid[r + 1][c]) &&
(grid[r][c] < grid[r][c + 1]) &&
(grid[r][c] < grid[r][c - 1])) {
return true;
}
else {
return false;
}
}
//峰值点和谷值点的位置以及海拔
void peakValleyPoint(int nrows,int ncols, const double grid[MAX_MAP][MAX_MAP]) {
//判断并打印峰值点和谷值点的位置
int peak = 0;
int valley = 0;
for (int i = 1; i < nrows - 1; i++) {
for (int j = 1; j < ncols - 1; j++) {
if (isPeak(grid, i, j)) {
cout << "峰值点为:" << "第" << i + 1 << "行" << "第" << j + 1 << "列 ";
cout << "值为:" << grid[i][j] << endl;
peak++;
}
else if(isValley(grid, i, j)){
cout << "谷值点为:" << "第" << i + 1 << "行" << "第" << j + 1 << "列 ";
cout << "值为:" << grid[i][j] << endl;
valley++;
}
}
}
cout << "共有" << peak << "个峰值点" << endl;
cout << "共有" << valley << "个谷值点" << endl;
}
//最高点和最低点位置与海拔
void extremes(const double grid[MAX_MAP][MAX_MAP], int row, int col) {
double max = grid[0][0];
double min = grid[0][0];
int pos[2][2] = { 0 };//pos[0][0] pos[0][1] 保存最高点的坐标 pos[1][0] pos[1][1] 保存最低点的坐标
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (max < grid[i][j]) {
max = grid[i][j];
pos[0][0] = i;
pos[0][1] = j;
}
if (min > grid[i][j]) {
min = grid[i][j];
pos[1][0] = i;
pos[1][1] = j;
}
}
}
printf_s("最高值在第%d行第%d列为%lf\n",pos[0][0]+1, pos[0][1]+1, max);
printf_s("最低值在第%d行第%d列为%lf\n",pos[1][0]+1, pos[1][1]+1, min);
}