📜  C++ fmod()

📅  最后修改于: 2020-09-25 07:40:49             🧑  作者: Mango

C++中的fmod() 函数计算分子/分母的浮点余数(四舍五入)

C++中的fmod() 函数计算分子/分母的浮点余数(四舍五入)。

fmod (x, y) = x - tquote * y

其中tquote被截断,即x / y的结果(四舍五入)。

fmod()原型[从C++ 11标准开始]

double fmod(double x, double y);
float fmod(float x, float y);
long double fmod(long double x, long double y);
double fmod(Type1 x, Type2 y); // Additional overloads for other combinations of arithmetic types

fmod() 函数接受两个参数,并返回double,float或long double类型的值。此函数在头文件中定义。

fmod()参数

fmod()返回值

fmod() 函数返回x / y的浮点余数。如果分母y为零,则fmod()返回NaN(非数字)。

示例1:fmod()如何在C++中工作?

#include 
#include 

using namespace std;

int main()
{
    double x = 7.5, y = 2.1;
    double result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    x = -17.50, y = 2.0;
    result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    return 0;
}

运行该程序时,输出为:

Remainder of 7.5/2.1 = 1.2
Remainder of -17.5/2 = -1.5

示例2:fmod() 函数用于不同类型的参数

#include 
#include 

using namespace std;

int main()
{
    double x = 12.19, result;
    int y = -3;
    
    result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    y = 0;
    result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;

    return 0;
}

运行该程序时,输出为:

Remainder of 12.19/-3 = 0.19
Remainder of 12.19/0 = -nan