【发布时间】: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]。所以你有未定义的行为。