C Programming - Floating Point Issues - Discussion

Discussion Forum : Floating Point Issues - Find Output of Program (Q.No. 1)
1.
What will be the output of the program?
#include<stdio.h>
int main()
{
    float a=0.7;
    if(a < 0.7)
        printf("C\n");
    else
        printf("C++\n");
    return 0;
}
C
C++
Compiler error
Non of above
Answer: Option
Explanation:

if(a < 0.7) here a is a float variable and 0.7 is a double constant. The float variable a is less than double constant 0.7. Hence the if condition is satisfied and it prints 'C'
Example:

#include<stdio.h>
int main()
{
    float a=0.7;
    printf("%.10f %.10f\n",0.7, a);
    return 0;
}

Output:
0.7000000000 0.6999999881

Discussion:
21 comments Page 1 of 3.

Potnuru said:   1 decade ago
Why does the float constant has 0.69999991 and why not 0.700000000 only? some one explain.

Thangavel.V said:   1 decade ago
First what you should know float range value and double range value before to find out solution:

The range of double is -1.7e-308 to 1.7e+308.
The range of float is -3.4e-38 to 3.4e+38.

They are given float a=0.7---->(double constant,0.7)
(float value,a)
printf("%.10f %.10f\n",0.7, a);

0.7000000000 0.6999999881

Just you consider range value and solve it...whatever i know that only put.

John said:   1 decade ago
Im not able to get it can someone give me a clear explanation.

Nive said:   1 decade ago
#include<stdio.h>
int main()
{
float a=0.8;
if(a < 0.8)
printf("C\n");
else
printf("C++\n");
return 0;
}

why it prints the c++ as output? pls xplain..........

Kedar said:   1 decade ago
Ya i agree with nive, initialise a=0.1 and check if a < 0.1

it prints C++ !!

Manoj said:   1 decade ago
Fantastic.

Krishna said:   1 decade ago
Why there float a=0.7 ----> (double constant, 0.7)

Shak said:   1 decade ago
#include<stdio.h>
int main()
{
float a=0.8;
if(a < 0.8)
printf("C\n");
else
printf("C++\n");
return 0;
}

Why it prints the c++ as output? please explain.

Shiwam said:   1 decade ago
Hey gys!
it prints c++ for a=0.1 to 0.6
and from 0.7 and afterwards it prints c.
again from 0.8 it prints c++.
it implies 0.7 is a special case that may be related to range of float and double.
so i m searching and pls you also.
Good luck.

Raghav Naganathan said:   1 decade ago
Guys...if the condition if(a < 0.7f) is used, then the output is c++, as 0.7f is a float constant and 0.7 is not less than 0.7 (as it is equal).

Hope this helps.


Post your comments here:

Your comments will be displayed after verification.