1 Attachment(s)
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.
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.
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;
}