Datatypes Justify Output

#include
void main()
{
float a=0.7;
if(a<0.7)
printf("yes");
else
printf("no");
}
what is the answer and reason.

Questions by patchillaramkumar

Showing Answers 1 - 5 of 5 Answers

All floating point values are stored as double. So in the given program the value of variable "a" is interpreted as 0.69999999 thus "double" is truncated to "float".

Even Some compillers will generate a warning as follows :

initializing' : truncation from 'double' to 'float'

This is one possible reason for the wrong output.

NOTE : Also during condition checking , there will be implicit type conversion among the different data types and their values thus leading to unexpected results.So one should be very careful when checking for variables of different data types.

The if condition in the above can be modified as

if(a < (float)0.7) to get the correct output(expected output).

When
a = 0.7
internally compiler treats 0.7 as double.
Now a is a float and float is always small then double so the if condition is true and answer will be

YES

  Was this answer useful?  Yes


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


void main(voif)
{
float a=0.9,b=0.9;
double c=0.9;
if(a<b)
printf("yes for b");
else
printf("no for b");

if(a<c)
printf("nyes for c");
else
printf("nno for c");

getch();   
}

Output:
no for b
yes for c

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions