📜  C++ restder()

📅  最后修改于: 2020-09-25 08:02:02             🧑  作者: Mango

C++中的restder() 函数计算分子/分母的浮点余数(四舍五入到最接近的值)。

C++中的restder() 函数计算分子/分母的浮点余数(四舍五入到最接近的值)。

remainder (x, y) = x - rquote * y

其中rquotex/y的结果,四舍五入到最接近的整数值(中途情况四舍五入到偶数)。

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

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

restder() 函数采用两个参数,并返回double,float或long double类型的值。

此函数在头文件中定义。

restder()参数

restder()返回值

restder() 函数返回x/y的浮点余数(四舍五入到最接近的值)。

如果分母y为零,则restder()返回NaN (非数字)。

示例1:剩下的()如何在C++中工作?

#include 
#include 

using namespace std;

int main()
{
    double x = 7.5, y = 2.1;
    double result = remainder(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;

    x = -17.50, y=2.0;
    result = remainder(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    y=0;
    result = remainder(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    return 0;
}

运行该程序时,输出为:

Remainder of 7.5/2.1 = -0.9
Remainder of -17.5/2 = 0.5
Remainder of -17.5/0 = -nan

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

#include 
#include 

using namespace std;

int main()
{
    int x = 5;
    double y = 2.13, result;
    
    result = remainder(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;

    return 0;
}

运行该程序时,输出为:

Remainder of 5/2.13 = 0.74