#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__cdeclprintf(constchar*format,...)/** stdout ''PRINT'', ''F''ormatted*/{va_listarglist;intbuffing;intretval;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);}
本文探讨了使用C语言printf函数输出整数时遇到的特殊现象。当试图以浮点数格式输出整数值65535时,输出结果为0而非预期值,文章深入分析了这一现象背后的技术原理,并提供了正确的输出方式。
4348

被折叠的 条评论
为什么被折叠?



