在C中打印特定数据类型的值?

时间:2014-11-09 04:57:17

标签: c

我试图打印出三列:

值:数据类型:大小(以字节为单位):

到控制台:

#include <stdio.h>
/*
print out the primitive (basic built in) data types for C
along with their size in bytes.
*/
int main(){
    char letter = 'j';
    short int x = 55437;
    long int y = 1234567;
    double dbl = 5.99;
    float boobs = 4.66;

    printf("Value:    Datatype:  Size(in bytes):\n\n");

    printf("%c\t  char\t   %c\n", letter, sizeof(letter));
    printf("%d\t  short\t   %d\n", x, sizeof(x));
    printf("%ld\t  long\t   %ld\n", y, sizeof(y));
    printf("%lf\t  double\t   %lf\n", dbl, sizeof(dbl));
    printf("%f\t  float\t   %f\n", boobs, sizeof(boobs));
}

我几乎得到了它,但我仍然有一些不正确的输出: new problems

为什么我的short int打印为-10099(与我已经将其分配给55437相矛盾)?为什么我的数据类型列中的double和float数据类型说明符被移动到目前为止?

3 个答案:

答案 0 :(得分:1)

"%c"中使用printf打印值时,会将其转换为unsigned char。但是,对于ASCII,只有0x200x7E的值为printable characters。如何显示其他字符取决于终端。

答案 1 :(得分:1)

试试这个

printf("%c\tchar\t   %d\n", letter, (int)sizeof(letter));
printf("%hd\tshort\t   %d\n", x, (int)sizeof(x));//55437 > max of int16
printf("%ld\tlong\t   %d\n", y, (int)sizeof(y));
printf("%f\tdouble\t   %d\n", mile, (int)sizeof(mile));
printf("%f\tfloat\t   %d\n", wage, (int)sizeof(wage));

答案 2 :(得分:0)

试试这个:)

printf("%c\t  char\t   %g\n", letter, sizeof(letter));
printf("%d\t  short\t   %g\n", x, sizeof(x));
printf("%ld\t  long\t   %g\n", y, sizeof(y));
printf("%g.2\t  double\t   %g\n", dbl, sizeof(dbl));
printf("%f.2\t  float\t   %g\n", boobs, sizeof(boobs));