为什么我的Quicksort算法列表中有一个0浮点,以及如何在我的Quicksort算法中包含NaN? [英] Why is there a 0 floating point in my Quicksort algorithm list and how to include a NaN into my Quicksort algorithm?

查看:71
本文介绍了为什么我的Quicksort算法列表中有一个0浮点,以及如何在我的Quicksort算法中包含NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <limits>

#define INFINITY std::numeric_limits<float>::infinity()
#define NEGINFINITY -std::numeric_limits<float>::infinity()

int floatcomp(const void* elem1, const void* elem2)
{
    if (*(const float*)elem1 < *(const float*)elem2)
        return -1;
    return *(const float*)elem1 > *(const float*)elem2;
}

int main()
{
    float array[10] = {INFINITY, 3.5f, 144.4f, NAN, 12.4f, NEGINFINITY, 1.4f, -0.0f, 5.9f};
    int i;

    for (i = 0; i < 10; i++)
        printf("%f\n", array[i]);
    printf("\n");

    qsort(array, 10, sizeof(float), floatcomp);

    for (i = 0; i < 10; i++)
        printf("%f\n", array[i]);

    return 0;
}       

快速排序算法以正确的顺序对输入的数字进行排序,但是列表中始终存在0.00000.

The quicksort algorithm sorts the numbers entered in the correct order however, there is a 0.00000 always present in the list.

另外,在将NaN添加到数组时,NaN的排序不正确,因此我无法正确地将NaN的两个尾数添加到我的代码中,作为顶部的字符串.

Also while adding the NaN to the array, the NaN is not sorted properly as it should be and I'm not able to correctly add in two different mantissa's for the NaN into my code as a string at the top.

推荐答案

要回答为什么总是包含零,这是因为您声明了一个由10个元素组成的数组,但是仅用9个元素对其进行了初始化,因此第10个元素是零.

To answer why there is a zero always included, that's because you are declaring an array of 10 elements, but you initialize it with only 9, so the 10th is zero.

对于NaN,您应该准确解释对NaN正确"排序的定义是什么,以及结果与预期的差异如何.

As for the NaN, you should explain precisely what your definition of sorting a NaN "properly" is, and how the result differs from what you expected.

这篇关于为什么我的Quicksort算法列表中有一个0浮点,以及如何在我的Quicksort算法中包含NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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