C Programming - Floating Point Issues

Exercise : Floating Point Issues - Find Output of Program
6.
What will be the output of the program?
#include<stdio.h>
int main()
{
    float f=43.20;
    printf("%e, ", f);
    printf("%f, ", f);
    printf("%g", f);
    return 0;
}
4.320000e+01, 43.200001, 43.2
4.3, 43.22, 43.21
4.3e, 43.20f, 43.00
Error
Answer: Option
Explanation:

printf("%e, ", f); Here '%e' specifies the "Scientific Notation" format. So, it prints the 43.20 as 4.320000e+01.

printf("%f, ", f); Here '%f' specifies the "Decimal Floating Point" format. So, it prints the 43.20 as 43.200001.

printf("%g, ", f); Here '%g' "Use the shorter of %e or %f". So, it prints the 43.20 as 43.2.


7.
What will be the output of the program?
#include<stdio.h>
int main()
{
    float a=0.7;
    if(a < 0.7f)
        printf("C\n");
    else
        printf("C++\n");
    return 0;
}
C
C++
Compiler error
Non of above
Answer: Option
Explanation:

if(a < 0.7f) here a is a float variable and 0.7f is a float constant. The float variable a is not less than 0.7f float constant. But both are equal. Hence the if condition is failed and it goes to else it prints 'C++'
Example:

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

Output:
0.6999999881 0.6999999881


8.
What will be the output of the program?
#include<stdio.h>
#include<math.h>
int main()
{
    float n=1.54;
    printf("%f, %f\n", ceil(n), floor(n));
    return 0;
}
2.000000, 1.000000
1.500000, 1.500000
1.550000, 2.000000
1.000000, 2.000000
Answer: Option
Explanation:

ceil(x) round up the given value. It finds the smallest integer not < x.
floor(x) round down the given value. It finds the smallest integer not > x.

printf("%f, %f\n", ceil(n), floor(n)); In this line ceil(1.54) round up the 1.54 to 2 and floor(1.54) round down the 1.54 to 1.

In the printf("%f, %f\n", ceil(n), floor(n)); statement, the format specifier "%f %f" tells output to be float value. Hence it prints 2.000000 and 1.000000.


9.
What will be the output of the program?
#include<stdio.h>
int main()
{
    float d=2.25;
    printf("%e,", d);
    printf("%f,", d);
    printf("%g,", d);
    printf("%lf", d);
    return 0;
}
2.2, 2.50, 2.50, 2.5
2.2e, 2.25f, 2.00, 2.25
2.250000e+000, 2.250000, 2.25, 2.250000
Error
Answer: Option
Explanation:

printf("%e,", d); Here '%e' specifies the "Scientific Notation" format. So, it prints the 2.25 as 2.250000e+000.

printf("%f,", d); Here '%f' specifies the "Decimal Floating Point" format. So, it prints the 2.25 as 2.250000.

printf("%g,", d); Here '%g' "Use the shorter of %e or %f". So, it prints the 2.25 as 2.25.

printf("%lf,", d); Here '%lf' specifies the "Long Double" format. So, it prints the 2.25 as 2.250000.