modf()函数详解

首页 / C++入门教程 / modf()函数详解

此函数用于将数字分为整数和小数部分。

例如:

2.16 = 2 + 16

modf - 语法

假设数字是" x",而" ptr"是指向整数部分的指针。

float modf(float x, float* ptr);
double modf(double x, double* ptr);
long double modf(long double x, long double* ptr);
double modf(integral x, double* ptr);

modf - 参数

x :  该值分为两部分,即(小数和整数部分)。

ptr :它是存储x的整数部分的对象的指针。

modf - 返回值

它返回x的整数部分。

modf - 例子1

让我们看一个简单的例子

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
 float x=18.26;
 double ptr;
 float i=modf(x,&ptr);
 std::cout << "Value of x is : " <<x <<std::endl;
 cout<<"integral part of x is :"<<ptr<<'\n' ;
 cout<<"fractional part of x is :"<<i;
 return 0;
}

输出:

Value of x is : 18.26
integral part of x is :18
fractional part of x is :0.26

在此示例中,modf()函数将数字分为小数和整数部分。小数部分为0.26,整数部分为18。

modf - 例子2

让我们看一个简单的例子,当x的值为负时。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-math-modf-function.html

来源:LearnFk无涯教程网

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float x= -78.34;
    double ptr;
    float n=modf(x,&ptr);
    std::cout << "Value of x is : " <<x <<std::endl;
    cout<<"integral part of x is :"<<ptr<<'\n' ;
    cout<<"fractional part of x is :"<<n;
    return 0;
} 

输出:

Value of x is : -78.34
integral part of x is :-78
fractional part of x is :-0.339996

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

MySQL实战45讲 -〔林晓斌〕

RPC实战与核心原理 -〔何小锋〕

架构实战案例解析 -〔王庆友〕

爆款文案修炼手册 -〔乐剑峰〕

如何落地业务建模 -〔徐昊〕

Redis源码剖析与实战 -〔蒋德钧〕

Web漏洞挖掘实战 -〔王昊天〕

网络排查案例课 -〔杨胜辉〕

互联网人的数字化企业生存指南 -〔沈欣〕

好记忆不如烂笔头。留下您的足迹吧 :)