c++ 中浮点数取余

运算符% a一般用于整形之间使用,而对于浮点数需要使用函数

fmodf用于float型变量操作

fmod用于double型变量操作

modl用于long double型变量操作

 

这里使用fmod(), 下面示例从键盘获得一个整形范围的数并且需要输入 整形数据

#include <iostream>                                                              
#include <climits>
#include <cmath>
using namespace std;

bool is_int(double x) 
{
    if (x <= INT_MAX && x >= INT_MIN && fmod(x,1.0) == 0) 
        return true;
    else return false;
}

int main()
{
    double num;
    cout << "Yo , dude ! Enter as integer value: ";
    cin >> num;
    while (!is_int(num))
    {  
        cout << "Out of range -- please try again: ";
        cin >> num;
    }  

    int val = int (num);
    cout << "you've entered the integer " << val << "\nBye\n";

    return 0; 
}

 

posted @ 2021-01-03 12:00  miaorn  阅读(5368)  评论(0编辑  收藏  举报