代码解读
完整代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define N 64
bool isPeak(int map[N][N],int nrows,int ncols);
int main(void){
int nrows,ncols;
int map[N][N];
string filename;
ifstream file;
cout<<"请输入文件名:\n";
cin>>filename;
file.open(filename.c_str());
if(file.fail()){
cout<<"文件打开出错\n";
exit(1);
}
file>>nrows>>ncols;
if(nrows>N||ncols>N){
cout<<"网格太大,调整程序\n";
exit(1);
}
//从文件读取数据到二维数组
for(int i=0;i<nrows-1;i++){
for(int j=0;j<ncols-1;j--){
file>>map[i][j];
}
}
//判断并打印峰值的位置
for(int i=1;i<nrows-1;i++){
for(int j;j<ncols-1;j++){
if(isPeak(map,i,j)){
cout<<"峰点出现在行"<<i<<"列"<<j<<"的位置\n";
}
}
}
system("pause");
//关闭文件
file.close();
return 0;
}
bool isPeak(int map[N][N],int nrows,int ncols){
if((map[nrows][ncols]>map[nrows-1][ncols])&&
(map[nrows][ncols]>map[nrows+1][ncols])&&
(map[nrows][ncols]>map[nrows][ncols-1])&&
(map[nrows][ncols]>map[nrows][ncols+1])){
return true;
}
return false;
}
string类型的变量filename,用于保存获取到的用户输入的文件名
string filename;
cout<<"请输入文件名:\n";
cin>>filename;
创建file类,便于后面对于文件打开和关闭等的操作
ifstream file;
从文件读取数据到二维数组,直接将在文件中读取到的对应位置的数据 存储到代码开始创建的二维数组中
file>>map[i][j];
运行问题
Segmentation fault (core dumped)
具体是什么问题不太清楚,课件给的代码是可以成功运行的,我的代码和课件给的代码只有细微的差别,个人觉得这些的差别并不会导致这个报错。具体的问题还没有找到。
课件代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define N 64
bool isPeak(const double grid[][N], int r, int c);
int main(){
int nrows, ncols;
double map[N][N];
string filename;
ifstream file;
cout <<"请输入文件名.\n";
cin >> filename;
file.open(filename.c_str());
if(file.fail()){
cerr<<"打开输入文件出错.\n";
exit(1);
}
file>>nrows>>ncols;
if(nrows > N || ncols > N){
cerr<<"网格太大,调整程序.\n";
exit(1);
}
//从数据文件读数据到数组
for(int i=0; i<nrows; ++i){
for(int j=0; j<ncols; ++j){
file>>map[i][j];
}
}
//判断并打印峰值位置
for(int i=1;i<nrows-1; ++i){
for(int j=1;j<ncols-1; ++j){
if(isPeak(map, i, j)){
cout<<"峰值出现在行: "<<i<<" 列:"<<j<<endl;
}
}
}
//关闭文件
file.close();
//结束程序
return 0;
}
bool isPeak(const double grid[][N], int i, int j){
if((grid[i-1][j]<grid[i][j]) &&
(grid[i+1][j]<grid[i][j]) &&
(grid[i][j-1]<grid[i][j]) &&
(grid[i][j+1]<grid[i][j]))
return true;
else
return false;
}