气泡以C,NAN,INFINITY和

编程入门 行业动态 更新时间:2024-10-28 02:24:48
本文介绍了气泡以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.

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

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和

本文发布于:2023-10-16 11:21:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:气泡   NAN   INFINITY

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!