brianjay0914

Estimable
May 5, 2014
14
0
4,570
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

Judicious
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

Judicious
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

Judicious
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.