.txt 数组计算局部最大值

在文本文件中,第一行包含一个整数(不超过 10000 ) - 数组中元素的数量,在接下来的行中 - 每行一个整数 - 此数组的元素。计算数组中局部最大值的个数(局部最大值严格大于相邻数组元素,第一个和最后一个数组元素肯定不是局部最大值)。所有数字都在 -10 ^ 9 到 10 ^ 9 的范围内。
输出数据格式
写出结果如下:在第一行 - 由单个空格分隔的数组元素,在第二行 - 定义了局部最大值的那些数组元素的索引,按降序排列(元素的索引从一个开始) .如果数组为空,则创建一个空的输出文件。输出文件中的行首和行尾不允许有空格。

img


#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
int main(){
    char IndexResult[10001][100];
    FILE *infile,*outfile;
    infile = fopen("E:/C/Test/1.txt","r");
    outfile = fopen("E:/C/Test/2.txt","w+");
    if(!infile||!outfile){
        printf("file couldn't be open!");
        return -1;
    }
    int num,i,length=0;
    int grand,father,son;
    fscanf(infile,"%d",&num); 
    fscanf(infile,"%d",&grand);
    fscanf(infile,"%d",&father);
    fscanf(infile,"%d",&son);
    if(father>grand&&father>son){
        sprintf(IndexResult[length++],"%d",2);
    }
    fprintf(outfile,"%d %d %d ",grand,father,son);
    for(i=4;i<=num;i++){
        grand=father;father=son;
        fscanf(infile,"%d",&son);
        fprintf(outfile, "%d ",son);
        if(father>grand&&father>son){
            sprintf(IndexResult[length++],"%d",(i-1));
        }
    }
    fputc('\n',outfile);
    for(i=length-1;i>=0;i--){
         fprintf(outfile, "%s ",IndexResult[i]);
    }
    fclose(outfile);
    fclose(infile);
}

img

难度:简单
读取文件数据,判断某个元素是否比前后两个元素大即可,判断过程中纪录下标,最后倒序输出即可!

PS:有问题可以再问我,学习数据结构和算法、C/C++、Linux可以关注我。