Thursday, 26 December 2013

Trap #1 :Error: Illegal Use Of Floating Point

There are  times when we write codes according to problem statement, Run it, and never be able to debug it.
Error: Illegal Use Of Floating Point is one such error. The problem is with the % operator you have used.

We all use '%' operator known as modulus operator in C. Lets focus on some facts about it :
  1. % operator gives Remainder of Division of the two numbers.
    Ex. 20 % 3 = 2
  2. On focusing a bit it will be clear that % operator gives its value in an int form.
  3. Hence its defined only for integer type variables. The above error occurs because you ave used % with a float type variable or constant.Ex #1:
    #include<stdio.h>
    main()
    {
    int a=20,b=3,c; //NO ERROR
    c=a%b;
    printf("%d",c);
    }
    ####No Error Output = 2

    Ex #2:
    #include<stdio.h>
    main()
    {
    float a=20,b=3,c;
    c=a%b;
    printf("%f",c);
    }
    ###Error illegal use of floating point
  4. If you want to use it with float values only then there is a solution for it too:
    use of fmod() Function defined under <math.h> library.

No comments:

Post a Comment