Wrong Format
Using %f to print an integer
The bad program
#include <stdio.h>
#include <stdlib.h>
/* This is why you should compile with -Wall */
int main(int argc, char *argv[]) {
printf("2 is %8d, 3 is %8d, 5 is %8d\n", 2, 3, 5) ;
printf("2 is %8f, 3 is %8d, 5 is %8d\n", 2, 3, 5) ;
printf("2 is %8d, 3 is %8f, 5 is %8d\n", 2, 3, 5) ;
printf("2 is %8d, 3 is %8d, 5 is %8f\n", 2, 3, 5) ;
return EXIT_SUCCESS ;
}
The result
2 is 2, 3 is 3, 5 is 5
2 is 0.000000, 3 is 5, 5 is 12625408
2 is 2, 3 is 0.000000, 5 is 12625408
2 is 2, 3 is 3, 5 is 0.000000
Using %f, not %lf, to read a double
The bad program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
float twoF, threeF, fiveF ;
double twoD, threeD, fiveD ;
puts("Always enter: 2 3 5") ;
scanf("%f%f%f", &twoF, &threeF, &fiveF) ;
printf("2 is %8f, 3 is %8f, 5 is %8f\n", twoF, threeF, fiveF) ;
scanf("%f%f%f", &twoD, &threeD, &fiveD) ;
printf("2 is %8f, 3 is %8f, 5 is %8f\n", twoD, threeD, fiveD) ;
scanf("%lf%lf%lf", &twoD, &threeD, &fiveD) ;
printf("2 is %8f, 3 is %8f, 5 is %8f\n", twoD, threeD, fiveD) ;
return EXIT_SUCCESS ;
}
The result
Always enter: 2 3 5
2 3 5
2 is 2.000000, 3 is 3.000000, 5 is 5.000000
2 3 5
2 is 0.000000, 3 is 0.000000, 5 is 0.000000
2 3 5
2 is 2.000000, 3 is 3.000000, 5 is 5.000000
Reading a float into an integer
The bad program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int m ;
int n ;
m = 2 ;
n = 3 ;
printf("m is %d, n is %d\n", m, n) ;
printf("\nEnter a value for m\n") ;
scanf("%d", &m) ;
printf("m is %d, n is %d\n", m, n) ;
printf("\nEnter a value for m\n") ;
scanf("%f", &m) ;
printf("m is %d, n is %d\n", m, n) ;
printf("\nEnter a value for m\n") ;
scanf("%lf", &m) ;
printf("m is %d, n is %d\n", m, n) ;
return EXIT_SUCCESS ;
}
The result
m is 2, n is 3
Enter a value for m
2
m is 2, n is 3
Enter a value for m
2
m is 1073741824, n is 3
Enter a value for m
2
m is 0, n is 1073741824