问题
I have been experimenting with the bubble sort code as I have recently started to gain my knowledge of C code. However I am unable to input NAN into the code for it to print out when building and running it. I am having the same problem with INFINITY AND -INFINITY. The code, however, works when I run the code and input NAN, INFINITY AND -INFINITY as one of the integers. Help would be appreciated, thanks.
/* Bubble sort code */
#include <stdio.h>
#include <math.h>
int main()
{
float array[100], swap;
int c, d, n;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%f", &array[c]);
for (c = 0; c < (n - 1); c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (array[d] > array[d + 1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%f\n", array[c]);
return 0;
}
回答1:
The floating point value NAN is unordered with respect to other values.
If a NAN value is an operand to the <, >, <=, >=, or == operators, the result will always evaluate to false. Also, if NAN is an operand of the != operator, the result will always be true. It follows from this that NAN != NAN is true and NAN == NAN is false.
Because of this, you won't get any meaningful results attempting to sort a list of floating point numbers that contains NAN. You need to check for this value using the isnan function and either ignore it or ask the user to enter a different number.
The values -inf and inf however are ordered. You can sort a list containing these values.
Using your existing code, we can see that inf and -inf are handled properly:
Enter number of elements
5
Enter 5 integers
3.5
infinity
2.9
9
-infinity
Sorted list in ascending order:
-inf
2.900000
3.500000
9.000000
inf
But NAN is not:
Enter number of elements
6
Enter 6 integers
8.4
7.5
nan
6.7
3.5
4.4
Sorted list in ascending order:
7.500000
8.400000
nan
3.500000
4.400000
6.700000
来源:https://stackoverflow.com/questions/42578497/bubble-sort-in-c-with-nan-infinity-and-infinity