C++如何檢查浮點數是否爲整數

如何檢查浮點數是否爲整數

今天在寫程序的時候,突然遇到這個問題——如何判斷一個浮點數小數點後是否有小數值?

剛開始想了一個比較麻煩的方法,感覺不妥,太浪費時間了,然後就上網看了一些其他人的思路,藉此總結一下幾種判斷方式。

Number 1: 向下向上取整法
int main() {
    float num1 = 10.0f;
    float num2 = 2.0f;
    double res = num1 / num2;
    if(ceil(res) == floor(res))							
        std::cout << "整數" << std::endl;
    else
        std::cout << "小數" << std::endl;
    return 0;
}

頭文件 <cmath>

ceil():Computes the smallest integer value not less than arg. —— 向上取整

floor() : Computes the largest integer value not greater than arg. —— 向下取整

向上,向下取整後相同,則爲整數

Number 2: fmod 浮點取餘法
int main() {
    float num1 = 10.0f;
    float num2 = 2.0f;
    double res = num1 / num2;
    if(fmod(res,1.0)==0.0)
        std::cout << "整數" << std::endl;
    else
        std::cout << "小數" << std::endl;
    return 0;
}

頭文件 <cmath>

double fmod( double x, double y ): Computes the floating-point remainder of the division operation x/y.——浮點型取餘,例如 fmod(10.1,3.1) = 0.8 ,可以自行體會一下

浮點型取餘後爲0,則爲整數

推薦一片博文:浮點型取餘與%的區別

Number 3: modf 整數小數分離法
int main() {
    float num1 = 10.0f;
    float num2 = 2.0f;
    double res = num1 / num2;
    double interger  = 0 ;                  	//用來存放整數
    if(modf(res,&interger) == 0.0)
        std::cout << "整數" << std::endl;
    else
        std::cout << "小數" << std::endl;
    return 0;
}

頭文件 <cmath>
double modf( double x, double* iptr ):Decomposes given floating point value x into integral and fractional parts——分解浮點數爲整數和小數

x是要檢驗的數據;

iptr:是一個存放整形變量的地址,類型是double;

返回值:返回值是小數點後的值

返回值如果爲0.0,即爲整形

Number 4: 作差法(最簡單)
int main() {
    float num1 = 10.0f;
    float num2 = 2.0f;
    double res = num1 / num2;
    if(res - int(res) == 0)
        std::cout << "整數" << std::endl;
    else
        std::cout << "小數" << std::endl;
    return 0;
}

int(res):強制類型轉換爲整形,然後浮點型與整形作差

如果爲0,則爲整形

恕我把最簡單的放在最後,目的爲了大家多學點東西。如果有更好的想法,也可以寫下來,互相學習!

。◕‿◕。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章