【问题标题】:How to modify values within an array sequentially如何按顺序修改数组中的值
【发布时间】:2019-01-17 23:42:00
【问题描述】:

我正在尝试对数组进行排序,以便将值从最大到最小排序。

然后我想通过从较高的索引值中减去 1 并将较低的索引值加 1 来修改这些值,以便没有两个值相等。

我已经设法按我想要的方式对值进行排序,但我一直坚持如何修改数组值,以便没有两个相等。我应该如何处理这个问题?

#include <stdio.h>
#include <stdlib.h>

/*declare variables*/
int s, t, c, l, e;
int RawVals[5];

/*this sorts an input array from largest to smallest*/
int cmpfunc (const void *a, const void *b)
{
  return (*(int *) b - *(int *) a);
}

/* DiePyramid Generator */
int main ()
{
/*Value inputs are taken here*/
  printf ("Enter Skill Level, "), scanf ("%d", &s);
  printf ("Enter Applied Tags, "), scanf ("%d", &t);
  printf ("Enter characteristic Value, "), scanf ("%d", &c);
  printf ("Enter Enhanced Tags, "), scanf ("%d", &e);
  printf ("Enter Legendary Tags, "), scanf ("%d", &l);

/*These inputs are then put into the RawVals array*/
  RawVals[0] = s;
  RawVals[1] = t;
  RawVals[2] = c;
  RawVals[3] = e;
  RawVals[4] = l;

/*Print RawVals before sorting*/
  printf("\n");
  printf("Entered Array: ");
  for (int i=0;i<5;i++){
    printf("%d ", RawVals[i]);
  }

/*This function then takes the RawVals array, and sorts it using cmpfunc*/
  qsort (RawVals, 5, sizeof (int), cmpfunc);

/*Add in some spacing between array outputs*/
  printf("\n");
  printf("\n");

/*This prints out the values in the RawVals array after sorting*/
  printf(" Sorted Array: ");
  for (int i=0; i<5; i++){
      printf ("%d ", RawVals[i]);
    }

/*Pyramid Forming Function*/    
  for (int i=0;i<5;i++){
    int j = 0;
    int k = 1;
    for (int p=0;p<5;p++){
      if (RawVals[j] >= RawVals[k]){
        if (RawVals[j] > 0){
          RawVals[j]++;
          RawVals[k]--;
        }
      }
    j++;
    k++;
    }
  }

/*Print out the modified values that now form the pyramid*/
  printf("\n");
  printf("\n");
  printf(" Modded Array: ");
    for (int i=0; i<5; i++){
        printf ("%d ", RawVals[i]);
      }
}

使用上面的,

输入 1 2 2 4 5 应该给我 5 4 3 2 0

实际输出为 10 4 -3 7 -4

【问题讨论】:

  • /*Pyramid Forming Function*/部分变量int k = 1可以在最后一次i循环迭代中索引超出范围,并访问RawVals[5]。所以你有未定义的行为

标签: c sorting numbers


【解决方案1】:

正如 Weather Vane 指出的那样,k 正在超越终点。

另外,您的外部if 条件不正确。应该是== 而不是&gt;=

这是更正后的代码。

请注意 pfor 循环中的更改,以防止 k 过高(即它应该只进行 4 次迭代而不是 5 次)

/*Pyramid Forming Function*/
for (int i = 0; i < 5; i++) {
    int j = 0;
    int k = 1;

    for (int p = 1; p < 5; p++) {
        if (RawVals[j] == RawVals[k]) {
            if (RawVals[j] > 0) {
                RawVals[j]++;
                RawVals[k]--;
            }
        }
        j++;
        k++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多