printf 使用%f输出整形变量,为什么为0?

来源:互联网 发布:带着空间去民国淘宝 编辑:程序博客网 时间:2024/04/30 12:15

#include <stdio.h>

void main()

{ 

     int i = 65535;

    printf("%f",i)

}

1,之所以没输出65535,这是C语言设计的原因。

2,之所以输出0,这是计算机体系结构的问题。

具体原因如下(至今无标准答案)

1、printf函数不进行任何类型转换,它只是从内存中读出你所提供的元素的值(按照%d,%f等控制字符提示的格式)。int型以补码形式存储在内存中,而浮点型是按照指数形式存储的。

2、浮点数和整数在printf时访问数据的寄存器是不一样的,属于未定义行为,输出结果是随机的;因此如果需要将整形用浮点型格式输出之前需将整形强行转换为浮点型,如下所示:

#include <stdio.h>

void main()

{ 

     int i = 65535;

    printf("%f",(float)i)

}

附 printf.c 的源码:

/***
*printf.c - print formatted
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines printf() - print formatted data
*
*******************************************************************************/
 
#include
#include
#include
#include
#include
#include
#include
 
/***
*int printf(format, ...) - print formatted data
*
*Purpose:
* Prints formatted data on stdout using the format string to
* format data and getting as many arguments as called for
* Uses temporary buffering to improve efficiency.
* _output does the real work here
*
*Entry:
* char *format - format string to control data format/number of arguments
* followed by list of arguments, number and type controlled by
* format string
*
*Exit:
* returns number of characters printed
*
*Exceptions:
*
*******************************************************************************/
 
int __cdecl printf (
const char *format,
...
)
/*
* stdout ''PRINT'', ''F''ormatted
*/
{
va_list arglist;
int buffing;
int retval;
 
va_start(arglist, format);
 
_ASSERTE(format != NULL);//断言宏。如果输出格式字符串指针为空,则在DEBUG版下断言,报告错误。
 
_lock_str2(1, stdout);
 
buffing = _stbuf(stdout);//stdout:指定输出到屏幕
 
retval = _output(stdout,format,arglist);
 
_ftbuf(buffing, stdout);
 
_unlock_str2(1, stdout);
 
return(retval);
}

0 0