我正在尝试对数组进行排序,以便将值从最大到最小排序。
然后我要修改这些值,以使两个值都不相等,方法是从较高的索引值中减去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
答案 0 :(得分:1)
正如风向标指出的那样,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++;
}
}