【问题标题】:array values changes after sorting in float variable在浮点变量中排序后数组值发生变化
【发布时间】:2016-03-21 01:14:40
【问题描述】:

我运行此代码并在数组“s”中输入浮点值,但排序后,数组元素的新值与输入值略有不同。为什么会这样? 这是我运行的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <conio.h>


void main()
{
    int N,sorted,i;

    printf("How many students?\n");
    scanf("%d",&N);
    float s[N],temp;

    for(i=0;i<N;i++)
    {
        printf("Marks of student %d?\n",i+1);
        scanf("%f",&s[i]);
    }
    //bubble sorting ---
    while(1)
    {
        sorted=0;
        for(i=0;i<N-1;i++)
        {
            if(s[i]<s[i+1])
            {
                temp=s[i];
                s[i]=s[i+1];
                s[i+1]=temp;
                sorted=1;
            }
        }
        if(sorted==0)
            break;
    }
    printf("\nSorted Marks - \n\n");
    for(i=0;i<N;i++)
    {
        printf("%f\n",s[i]);
    }
}

输入:

N=5
Marks = 34.53,54,34,56.76,87.567

输出:

Sorted Marks -

87.567001
56.759998
54.000000
34.529999
34.000000

【问题讨论】:

  • 阅读浮点精度。
  • 首先,请创建一个Minimal, Complete, and Verifiable Example 并向我们展示,包括变量声明。那你能告诉我们输入是什么,预期输出应该是什么,实际输出是什么。
  • 请编辑您的问题以包含代码、输入以及预期和实际输出。
  • 那么简短的回答是并非所有浮点数都可以精确存储,因此系统选择“最近”可能的数字,这可能导致例如34.53 成为34.529999。
  • 您可以通过两种方式“解决”问题。 1) 将scanf 中的float 更改为double,并将"%f" 更改为"%lf"。 2) 将printf 中的"%f" 更改为"%.4f"。

标签: c arrays sorting floating-point


【解决方案1】:

简短的回答是,并非所有浮点数都可以精确存储,因此系统会选择“最接近”的可能数字,这可能导致例如34.53 成为34.529999。 – 一些程序员老兄

您可以通过两种方式“解决”问题。 1) 将scanf 中的float 更改为double,并将"%f" 更改为"%lf"。 2) 将printf 中的"%f" 更改为"%.4f"。 – user3386109

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多