Exercise: Floating Point Issues

Questions for: Floating Point Issues

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;
}
A:
4.320000e+01, 43.200001, 43.2
B:
4.3, 43.22, 43.21
C:
4.3e, 43.20f, 43.00
D:
Error
Answer: A

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.

What will be the output of the program?
#include<stdio.h>
#include<math.h>
int main()
{
    printf("%d, %d, %d\n", sizeof(3.14f), sizeof(3.14), sizeof(3.14l));
    return 0;
}
A:
4, 4, 4
B:
4, 8, 8
C:
4, 8, 10
D:
4, 8, 12
Answer: C

sizeof(3.14f) here '3.14f' specifies the float data type. Hence size of float is 4 bytes.

sizeof(3.14) here '3.14' specifies the double data type. Hence size of float is 8 bytes.

sizeof(3.14l) here '3.14l' specifies the long double data type. Hence size of float is 10 bytes.

Note: If you run the above program in Linux platform (GCC Compiler) it will give 4, 8, 12 as output. If you run in Windows platform (TurboC Compiler) it will give 4, 8, 10 as output. Because, C is a machine dependent language.

What will be the output of the program?
#include<stdio.h>
#include<math.h>
int main()
{
    printf("%f\n", sqrt(36.0));
    return 0;
}
A:
6.0
B:
6
C:
6.000000
D:
Error: Prototype sqrt() not found.
Answer: C

printf("%f\n", sqrt(36.0)); It prints the square root of 36 in the float format(i.e 6.000000).

Declaration Syntax: double sqrt(double x) calculates and return the positive square root of the given number.

What will be the output of the program?
#include<stdio.h>
int main()
{
    float fval=7.29;
    printf("%d\n", (int)fval);
    return 0;
}
A:
0
B:
0.0
C:
7.0
D:
7
Answer: D

printf("%d\n", (int)fval); It prints '7'. because, we typecast the (int)fval in to integer. It converts the float value to the nearest integer value.

What will be the output of the program?
#include<stdio.h>
int main()
{
    float *p;
    printf("%d\n", sizeof(p));
    return 0;
}
A:
2 in 16bit compiler, 4 in 32bit compiler
B:
4 in 16bit compiler, 2 in 32bit compiler
C:
4 in 16bit compiler, 4 in 32bit compiler
D:
2 in 16bit compiler, 2 in 32bit compiler
Answer: A

sizeof(x) returns the size of x in bytes.
float *p is a pointer to a float.

In 16 bit compiler, the pointer size is always 2 bytes.
In 32 bit compiler, the pointer size is always 4 bytes.

Ad Slot (Above Pagination)
Quiz