1

I ran this code and input float values in array 's' but after sorting , new values of array elements are slightly different from input values. Why is it so ? This is the code I ran:

#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]);
    }
}

Input:

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

Output:

Sorted Marks -

87.567001
56.759998
54.000000
34.529999
34.000000
dragosht
  • 3,237
  • 2
  • 23
  • 32
Akhil Raj
  • 457
  • 1
  • 4
  • 14
  • 1
    Read about floating point precision. – haccks Dec 15 '15 at 09:55
  • 3
    First of all, please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us, including variable declarations. Then can you please tell us what the input is, what the expected output should be and what the actual output is. – Some programmer dude Dec 15 '15 at 10:00
  • And please *edit your question* to include the code, the input, and the expected and actual outputs. – Some programmer dude Dec 15 '15 at 10:03
  • You might want to read ["Is floating point math broken?"](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Some programmer dude Dec 15 '15 at 10:15
  • Tried to read it but couldn't understand it. New to c :( – Akhil Raj Dec 15 '15 at 10:23
  • 1
    Then the short answer is that not all floating-point numbers can be stored precisely, so the system chooses the "nearest" possible number, which can lead to e.g. `34.53` becomming `34.529999`. – Some programmer dude Dec 15 '15 at 10:30
  • 1
    You can "fix" the problem two ways. 1) Change `float` to `double`, and `"%f"` to `"%lf"` in the `scanf`. 2) Change `"%f"` to `"%.4f"` in the `printf`. – user3386109 Dec 15 '15 at 10:33
  • changing data type worked. Thanks . Changing %f to %.4f wasn't needed. – Akhil Raj Dec 15 '15 at 11:32

1 Answers1

0

The short answer is that not all floating-point numbers can be stored precisely, so the system chooses the "nearest" possible number, which can lead to e.g. 34.53 becomming 34.529999. – Some programmer dude

You can "fix" the problem two ways. 1) Change float to double, and "%f" to "%lf" in the scanf. 2) Change "%f" to "%.4f" in the printf. – user3386109

Armali
  • 18,255
  • 14
  • 57
  • 171