當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Math fmod()用法及代碼示例

該函數查找分子/分母的浮點餘數並四舍五入到零。

fmod 的公式:

fmod= numerator - t*denominator

其中 't' 是分子/分母的截斷值。

用法

考慮分子 'n' 和分母 'd'。語法是:

double fmod(double n,double d);

參數

n:分子的值。

d:分母的值

返回值

它返回 n/d 的浮點餘數。

注意:如果分母的值為零,則 fmod() 函數將返回 NAN(Not a Number)。

例子1

讓我們看一個具有相同類型參數的簡單示例。

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    double n=4.2;
    double d=7.8;
    std::cout << "The values of numerator and denominator are:" <<n<<" , "<< d<<     std::endl;
    std::cout << "fmod of these values is:"<<fmod(n,d) <<std::endl;
    return 0;
}

輸出:

The values of numerator and denominator are:4.2 , 7.8
fmod of these values is:4.2

例子2

讓我們看看具有不同類型參數的簡單示例。

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float n=7.8;
    int d=9;
    std::cout << "The values of numerator and denominator are:" <<n<<" , "<< d<< std::endl;
    std::cout << "fmod of these values is:"<<fmod(n,d) <<std::endl;
    return 0;
}

輸出:

The values of numerator and denominator are:7.8 , 9
fmod of these values is:7.8

例子3

讓我們看一個簡單的例子,當分母的值為零時。

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float n=16.7;
    int d=0;
    std::cout << "The values of numerator and denominator are:" <<n<<" , "<< d<< std::endl;
    std::cout << "fmod of these values is:"<<fmod(n,d) <<std::endl;
    return 0;
}

輸出:

The values of numerator and denominator are:16.7 , 0
fmod of these values is:-nan





相關用法


注:本文由純淨天空篩選整理自 C++ Math fmod()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。