c - 如何顺序修改数组中的值

标签 c sorting numbers

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

然后我想修改这些值,以便没有两个值相等,方法是从较高的索引值中减去 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

最佳答案

正如 Weather Vane 所指出的,k 将越过终点。

此外,您的外部 if 条件不正确。它应该是 == 而不是 >=

这是更正后的代码。

请注意 for 循环中 p 的变化,以防止 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++;
    }
}

关于c - 如何顺序修改数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245853/

相关文章:

c - 使用指针和 realloc 添加新记录

c - 力扣 : AddressSanitizer heap-buffer-overflow

arrays - 对快速数组进行排序并跟踪原始索引

arrays - 对数组进行垂直排序而不是水平排序

grails - View 中的grails数字( double )格式

c++ - C++返回字符数组相减的结果

c - 在 C 中使用递归缩进行

javascript数组读取表单数据最佳实践

java - 如何生成具有特定范围的唯一随机数

c# - 你能在不知道它们代表的数据类型的情况下比较两个存储为字符串的数字吗?