Results 1 to 3 of 3

Thread: Floating Point Number + NAN

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2008
    Posts
    474

    Floating Point Number + NAN

    Code:
    #include<stdio.h>
    #include<conio.h>
    float square(float);
    void main()
    {
        clrscr(); 
        float a,b;
        printf("ENter a Number");
        scanf("%f",&a);
        printf("Number=%f",a);
        b=square(a);
        printf("\nSquare of %f is %f",a,b);
       getch();
    }
    
    float square(float x)
    {
        float y;
        y=x*x;
        return(y);
    }
    In the above program, I am calculating the square of float number. But sometimes the number is entered as NAN and sometimes Output is NAN. What is NAN? I am entering floating point number, then y NAN is entered?
    SEE the Image attached for the OUTPUT.
    Attached Images Attached Images  

  2. #2
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,598

    Re: Floating Point Number + NAN

    NAN means Not A Number, so the conversion failed for some reason and the resulting bit pattern of the float is not a legal floating point format.
    I'm not sure why it would be failing. The code looks ok to me, other than the () around the return value, but I don't know C++ well enough to say whether than matters or not. You don't seem to be getting NAN on the result, but from scanf.
    Last edited by passel; May 8th, 2014 at 02:08 AM.

  3. #3
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,170

    Re: Floating Point Number + NAN

    What os/compiler are you using? return doesn't need () around the returned value but has no effect if present. You don't actually need to define y in square() as you can simply return the squared value. You are not checking to see if a valid number has been entered or not. Consider
    Code:
    #include <stdio.h>
    #include <conio.h>
    
    float square(float);
    
    void main()
    {
        //clrscr(); 
    float a;
    
    	if (printf("Enter a Number") > 0 && scanf("%f", &a))
    		printf("\nSquare of %f is %f", a, square(a));
    
    	//getch();
    }
    
    float square(float x)
    {
        return x * x;
    }
    Last edited by 2kaud; May 8th, 2014 at 04:04 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width