气泡以C,NAN,INFINITY和-INFINITY排序 [英] Bubble Sort in C with NAN, INFINITY AND -INFINITY

查看:123
本文介绍了气泡以C,NAN,INFINITY和-INFINITY排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着我最近开始了解C代码,我一直在尝试冒泡排序代码.但是,我无法在代码中输入NAN以便在构建和运行它时将其打印出来.我在INFINITY和-INFINITY上也遇到了同样的问题.但是,当我运行代码并将NAN,INFINITY和-INFINITY输入为整数之一时,该代码有效.非常感谢您的帮助.

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;
}

推荐答案

浮点值NAN与其他值无序.

如果NAN值是<><=>===运算符的操作数,则结果将始终为false.同样,如果NAN!=运算符的操作数,则结果将始终为true.因此,NAN != NAN为真,NAN == NAN为假.

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.

因此,尝试对包含NAN的浮点数列表进行排序时,不会得到任何有意义的结果.您需要使用isnan函数检查该值,然后忽略它或要求用户输入其他数字.

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.

但是,值-infinf是有序的.您可以对包含这些值的列表进行排序.

The values -inf and inf however are ordered. You can sort a list containing these values.

使用您现有的代码,我们可以看到inf-inf的处理正确:

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

但是NAN不是:

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

这篇关于气泡以C,NAN,INFINITY和-INFINITY排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆