Write a program to output an integer in decimal format and a floating point number in float format. Experiment with outputting an integer in float format and visa versa. Output a character in decimal format (prints the character code e.g. ascii). Fix any problems by using an explicit type coercion or cast.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {
    printf("Integer: %d\n", 10);
    printf("Float: %.1f\n", 10.5);
    printf("Integer in float format: %.1f\n", (float)10);
    printf("Float in integer format: %d\n", (int)15.6);
    printf("Character in decimal format: %d\n", 'a');
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Integer: 10
Float: 10.5
Integer in float format: 10.0
Float in integer format: 15
Character in decimal format: 97

Brief Explanation

  • The first printf function prints an integer in decimal format
  • The second printf function prints a floating point number in float format
  • The third printf function outputs an interger (10) in float format. Explicit type coercion "(float)10" is used to make that happen.
  • The fourth printf function outputs a float (15.6) in integer format. Type casting "(int)15.6" is used to make that happen.
  • The last printf function outputs the ASCII number of the character 'a'

Add comment


Security code
Refresh