(float)9/5只投9次而不是9/5的結果。所以/操作在這一點上不是一個整數操作。 (浮動)(9/5)將給出1.00000的結果。
嘗試編譯所有警告,它可能會告訴你很多錯誤。
例如一個64位的Linux系統上,用gcc編譯我-Wall得到:
pf.c: In function ‘main’:
pf.c:6:2: warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat]
pf.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘long unsigned int’ [-Wformat]
pf.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 5 has type ‘long unsigned int’ [-Wformat]
正如上面提到的,你需要正確的格式說明。使用正確的格式說明和鑄造給出:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("%f %f %lu %lu\n",(float)(9/5),(float)4,sizeof(float),sizeof(int));
return 0;
}
給出:
[email protected]:~/proj/c=>./pf
1.000000 4.000000 4 4
@Shahbaz現在,它不是標籤C++了,真 – MrRap