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的值为负时。

#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

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

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

即时消息技术剖析与实战 -〔袁武林〕

说透中台 -〔王健〕

打造爆款短视频 -〔周维〕

陈天 · Rust 编程第一课 -〔陈天〕

全链路压测实战30讲 -〔高楼〕

大厂设计进阶实战课 -〔小乔〕

计算机基础实战课 -〔彭东〕

AI 应用实战课 -〔黄佳〕

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