為什么最后輸出的numOne跟實(shí)際差距這么大,而且有時(shí)候還會(huì)是負(fù)整數(shù),是哪里錯(cuò)了?
#include <stdio.h>
int main()
{
? ? double numOne = 2.5; ? ? ?//定義浮點(diǎn)型變量num并賦值為2.5
? ? int numTwo = (int)numOne;
? ? printf("numOne的整數(shù)部分是%d\n",numOne);
? ? printf("numTwo的小數(shù)部分是%f\n",numTwo);
? ? return 0;
}
hello.c: In function 'main':
hello.c:6:38: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
? ? ?printf("numOne的整數(shù)部分是%d\n",numOne);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^
hello.c:7:38: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
? ? ?printf("numTwo的小數(shù)部分是%f\n",numTwo);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^
numOne的整數(shù)部分是1218162008
numTwo的小數(shù)部分是2.500000
2018-04-03
反了,%d才是整數(shù),,%f是6位小數(shù)。。。
2018-03-30
我不知道對(duì)不對(duì),但是這樣改了以后應(yīng)該是你想輸出的
#include <stdio.h>
int main()
{
? ? double numOne = 2.5; ? ? ?//定義浮點(diǎn)型變量num并賦值為2.5
? ? int numTwo = (int)numOne;
? ? printf("numOne的小數(shù)部分是%f\n",numOne);
? ? printf("numTwo的整數(shù)數(shù)部分是%d\n",numTwo);
? ? return 0;
}
2018-03-30
? ? 要注意%d是輸出帶符號(hào)的十進(jìn)制整數(shù),因?yàn)槟阍镜膎umOne是小數(shù),所以換算成整數(shù)則是不一致,還會(huì)帶有符號(hào)
? %f 是輸出6位小數(shù)? ? 可以再去看一下格式化輸出語句的部分
正確寫法應(yīng)該是
printf("numOne的整數(shù)部分是%f\n",numOne);
?printf("numTwo的小數(shù)部分是%d\n",numTwo);