Académique Documents
Professionnel Documents
Culture Documents
Data Types in C
Try breaking up
I have no idea the problem into
what is going smaller pieces
wrong here!
7
A Useful Tip While Solving Problems
Equals 0
A Useful Tip While Solving Problems
\t
\n
int k =5;
float x = k; // good implicit conversion, x gets 5.0
float y = k/10; // poor implicit conversion, y gets 0.0
float z = ((float) k)/10; // Explicit conversion by typecasting, z gets 0.5
float z = k/10.0; // this works too (explicit without typecasting), z gets
0.5 24
Typecasting: An Example Program
Also, typecasting But be careful about which
just one variable one you are typecasting
#include <stdio.h> on RHS is enough #include <stdio.h>
Typecasting
int main(){ int main(){ makes it
Several other ways
int total = 100, marks = 50;
also possible, e.g., int total = 100, marks=50;
50.0/100 which
float percentage; Equals 0 proper bracketing. float percentage; equals 0.5
percentage = (marks/total)*100; percentage = (float)marks/total*100;
printf("%.2f",percentage); printf("%.2f",percentage);
return 0; return 0;
0.00 50.00
} }
25
Typecasting is Nice. But Take Care..
#include <stdio.h> Expected #include <stdio.h>
int main(){ conversion int main(){
float x; int y; float x; int y;
x = 5.67; x = 1.0e50; // 10^50
y = (int) x; // typecast (convert) float to int y = (int) x; // typecast (convert) float to int
printf(“%d”,y); printf(“%d”,y);
return 0; 5 return 0; -2147483648
} }
Reverse typecasting error can happen too: No. 1.0e50 is too big to be
Sometimes converting a smaller data type cast as an int (or even Are you
(say int) to larger data type (say float) can long – try yourself) kidding?
also give unexpected results (more on this
later in the semester)
Unexpected!
26