? asked in 電腦與網際網路程式設計 · 1 decade ago

c語言 int轉成float floatj轉成int~~

整數轉為浮點數

#include <stdio.h>

#include<stdlib.h>

int main(void)

{

float intnum1 = 7;

float intnum2 = 3;

int answer;

answer = intnum1 / intnum2;

printf(" %d\n",answer);

system("pause");

return 0;

}

這時候浮點數就可以直接轉為整數

#include <stdio.h>

#include<stdlib.h>

int main(void)

{

int intnum1 = 7;

int intnum2 = 3;

float answer;

answer = intnum1 / intnum2;

printf(" %f\n",answer);

system("pause");

return 0;

}

這時候卻不行 但明明方法用的一樣

或是

#include <stdio.h>

#include<stdlib.h>

int main(void)

{

float intnum1 = 7;

float intnum2 = 3;

float answer;

answer = intnum1 / intnum2;

printf(" %d\n",(int)answer);

system("pause");

return 0;

}

這時候浮點數可以轉為整數

#include <stdio.h>

#include<stdlib.h>

int main(void)

{

int intnum1 = 7;

int intnum2 = 3;

int answer;

answer = intnum1 / intnum2;

printf(" %f\n",(float)answer);

system("pause");

return 0;

}

卻不行

要改成

#include <stdio.h>

#include<stdlib.h>

int main(void)

{

int intnum1 = 7;

int intnum2 = 3;

float answer;

answer = (float)intnum1 / intnum2;

printf(" %f\n",answer);

system("pause");

return 0;

}

這樣才行

這是為什麼呢? 請各位高手詳細解答小弟的疑問

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    <1>. intnum1=7.0, intnum2=3.0為float, 所以 intnum1 / intnum2=2.3為float

    但 answer 為int , 所以 intnum1 / intnum2轉成int 放入 answer=2

    <2>. intnum1=7, intnum2=3為int, 所以 intnum1 / intnum2=2為int

    但 answer 為float , 所以 intnum1 / intnum2轉成float放入answer=2.0

    <3>. intnum1=7.0, intnum2=3.0為float, 所以 intnum1 / intnum2=2.3為float

    answer也是float, 不用轉換 answer=2.3

    呼叫printf前,(int)answer轉成int=2(但沒放回answer, answer還是2.3)

    <4>.intnum1=7, intnum2=3為int, 所以 intnum1 / intnum2=2為int

    answer也是int, 不用轉換 answer=2

    呼叫printf前,(float)answer轉成float=2.0(但沒放回answer, answer還是2)

    <5>.intnum1=7, intnum2=3為int, (float)intnum1=7.0為float

    所以 (float)intnum1 / intnum2=2.3為float

    注意: (float)intnum1/intnum2與(float)(intnum1/intnum2)不一樣

    前者先轉換後計算, 後者先計算後轉換

    answer也是float, 不用轉換 answer=2.3

    2007-11-16 10:23:26 補充:

    計算方式:

    1.所有的數皆為int, 以int運算, 結果為int

    2.有一為float, 將所有int轉成float, 以float運算, 結果為float

  • Anonymous
    1 decade ago

    printf(" %f\n",(float)answer);

    這行只是顯示在更改它的內容顯示方式

    但answer記憶體內存放的值 已經拘限為整數了 因為你運算那行所致

    answer = (float)intnum1 / intnum2;

    其一個變數為分數 那麼算出來的值型態 就會剛著解析度大的跑

    float > int

    希望我說的對 XD

Still have questions? Get your answers by asking now.