Turbo C++ -nan problem

brianjay0914

Estimable
May 5, 2014
14
0
4,570
1
Heres what need to happen.
Enter two consecutive number , add them and show their average.


So The code is Quite correct
I can say

It worked before but if you try and try again .
and try to break it and it will

It'll show -NAN -NAN and -NAN


#include<stdio.h>
#include<conio.h>

float N1,N2,C,D,E;

main()
{
{
clrscr();
printf("Enter A Number:");
scanf("%f",&N1);
printf("Enter A Number Again:");
scanf("%f",&N2);
printf("%.2f and %.2f\n",N1,N2);
C=N2-N1;
D=N1+N2;
E=D*.50;

if(C!=1)
printf("Invalid");
{
if(C==1)
//printf("%f\n",D);
printf("%.2f",E);
}

}

getch();
return 0;
}




Tho it worked before . I want to know why it keeps happening when you try to break it . with same input or different.

what is -NAN how to prevent that from happening
 

kanewolf

Splendid
Moderator
NAN (or -NAN) is "not a number". Your scanf lines using the "%f" format will only accept floating point numbers. My guess (it has been a long time since I used Turbo C++) is that your float definition leaves the variables purposefully uninitialized. That is usually a compiler option. It is there to help developers.
 

kanewolf

Splendid
Moderator


Good point. You should always add a ".0" to ensure you are doing a floating point comparison. As it is, you are comparing a float to an int. There will be a standardized conversion done, but it is better to be explicit in your compare.
 

Adding ".0" (or ".0f") won't help when comparing 1.000000 to 0.9999999. The "correct" way of comparing floating point numbers is
Code:
if (fabs(n1-n2) < eps)
where "eps" is quite small number for magnitude of the numbers.
 

kanewolf

Splendid
Moderator


In the most generic sense, I would agree. In a practical sense, unnecessary. Human entered data in a program of this nature, that is unnecessarily complicated.
 
Thread starter Similar threads Forum Replies Date
F Apps General Discussion 5
J Apps General Discussion 0
P Apps General Discussion 4
I Apps General Discussion 2
kikani.kautik Apps General Discussion 2
synoptic12 Apps General Discussion 3
S Apps General Discussion 5
D Apps General Discussion 1
S Apps General Discussion 1
arpitsri Apps General Discussion 3
R Apps General Discussion 1
Lumia925 Apps General Discussion 1
S Apps General Discussion 2
S Apps General Discussion 3
I Apps General Discussion 3
arpitsri Apps General Discussion 2
Cube777 Apps General Discussion 2
gam0reily Apps General Discussion 2
K Apps General Discussion 1
A Apps General Discussion 2

ASK THE COMMUNITY