在C中找到数组的峰值数 [英] Finding the Peak number of an array in C

查看:69
本文介绍了在C中找到数组的峰值数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言编程的新手.我正在尝试编写一个代码,该代码可找到数组中的峰值,即大于该编号之前和之后的编号的数字.

I am new to coding in C. I am trying to write a code that finds the peak number in an array, that is the numbers that are greater than the numbers before and after said number.

这是我的代码.它运行没有错误,但是没有输出,所以我知道我做错了.

This is my code. It runs without error but no output so I know I am doing something wrong.

#include <stdio.h>
int main() {
 int nums[14] = {1, 2, 3, 3, 2, 4, 1, 5, 6, 3, 1, 10, 2, 8};
  int peaks[4];

 for(int i = 0; i < nums[i]; i++){
     if(nums[i] > nums[i-1] && nums[i] > nums[i+1]){
         peaks == nums[i];
     }
     return peaks;
 }

 printf("Peak numbers are %d",peaks);
}

如何获取它作为结果输出: [4、6、10、8]

How can I get it to output this as the result: [4, 6, 10, 8]

推荐答案

该程序适用于 nums 数组中任意个元素,并且考虑了第一个和最后一个元素正确.

This program works for any number of elements in the nums array and it takes into account the first and the last element correctly.

[sizeof(nums)/sizeof(nums [0]) nums 数组中的实际元素数,因此yolu可以将任意数量的元素放入 nums 数组,程序将始终正常运行

[sizeof(nums)/sizeof(nums[0]) is the actual number of elements in the nums array, therefore yolu can put any number of elements into the nums array and the program will always work correctly

peaks 的元素数也不再硬编码为 4 ,而是与 num 中的元素数相同,因此我们可以确保不会出现任何索引超出范围的问题.但是,由于大小为 n 的数组的最大峰数为 n/2 + 1 (不太确定),我们可以写出 int peaks [sizeof(nums)/sizeof(nums [0])/2 + 1]

Also the number of elements of peaks is no longer hard coded as 4 but the same as the number of elements in num, so we can insure that there won't be any index out of bounds problems. However as the maximum number of peaks of an array of size n is n/2 + 1 (not quite sure), we can probably write int peaks[sizeof(nums)/sizeof(nums[0])/2+1]

#include <stdio.h>

int main() {
  int nums[] = { 1, 2, 3, 3, 2, 4, 1, 5, 6, 3, 1, 10, 2, 8 };
  int peaks[sizeof(nums)/sizeof(nums[0])];
  int pi = 0;

  for (int i = 0; i < sizeof(nums)/sizeof(nums[0]); i++) {
    if (
        (i == 0 && nums[i + 1] < nums[i]) ||   /* first element */
        (i == sizeof(nums) / sizeof(nums[0]) && nums[i - 1] < nums[i]) || /* last element */
        (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) /* elements in the middle */
      )
    {
      peaks[pi++] = nums[i];
    }
  }

  for (int i = 0; i < pi; i++)
    printf("%d ", peaks[i]);
}

但是 if 语句中的条件可能可以用更优雅的方式编写.

However the condition in the if statement can possibly be written in a more elegant manner.

这篇关于在C中找到数组的峰值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆