Reputation: 13
I'm supposed to input real numbers until a input of 0 is encountered, then program should terminate. I got this code working for integer data type:
#include<stdio.h>
int main()
{
int i;
int a[60];
for(i=0;i<60;i++)
a[i]=-1;
for(i=0;;i++)
{
scanf("%d",&a[i]);
if(a[i]==0)
break;
}
return 0;
}
But when I try the same code on the double data type, program termination does not occur on input of 0. Here's the code:
#include<stdio.h>
int main()
{
int i;
double a[60];
for(i=0;i<60;i++)
a[i]=-1.0;
for(i=0;;i++)
{
scanf("%f",&a[i]);
if(a[i]==0.0)
break;
}
return 0;
}
Would anyone bother to explain why is this so? I can't think of any reason. Thank You in advance.
Upvotes: 1
Views: 81
Reputation: 22133
For one thing, your parse string is incorrect: for double it should be "%lf", not "%f", which is for floats.
Secondly, in general comparing floating-point types for equality is error-prone because they are by nature approximative, although in this case, 0 is a value that can be represented exactly.
Upvotes: 1