ch1-Truncate (float to int)

Chapter_1     Exercise_1-2     Temperature_Programs Exercise_1-3







truncate.c         download


#include <stdio.h> // for printf()

int main()
{
printf("5 / 2 = %d\n", 5 / 2); // truncate, print as int
printf("5.0 / 2 = %g\n", 5.0 / 2);
printf("5 / 2.0 = %g\n", 5 / 2.0);
printf("(float) (5 / 2) = %g\n", (float) (5 / 2)); // truncate: (float) 2
printf("(float) 5 / 2 = %g\n", (float) 5 / 2); // ((float) 5) / 2
printf("5 / (float) 2 = %g\n", 5 / (float) 2); // 5 / ((float) 2)

float x = 5, y = 2; // convert int to float in assignments
printf("x / y = %g\n", x / y);
}
/*
gcc truncate.c -o truncate
./truncate
5 / 2 = 2
5.0 / 2 = 2.5
5 / 2.0 = 2.5
(float) (5 / 2) = 2
(float) 5 / 2 = 2.5
5 / (float) 2 = 2.5
x / y = 2.5
*/





Note:  See also C_type_conversion on W3Schools, the C_Tutorial, chapter C_Data_Types.









Chapter_1     Exercise_1-2     Temperature_Programs BACK_TO_TOP Exercise_1-3



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo