trunc()函数以及C ++中的示例

C ++trunc()函数

trunc()函数cmath标头的库函数,用于将值四舍五入(截断)为零,它接受一个数字并返回其大小不大于给定数字的最近整数值。

trunc()函数语法:

    trunc(x);

参数: x –是要舍入为零的数字。

返回值: double-返回double类型的值,该值是数字x的舍入(截断)值。

示例

    Input:
    float x = 2.3;    
    Function call:
    trunc(x);    
    Output:
    2

    Input:
    float x = 2.8;
    Function call:
    trunc(x);    
    Output:
    2

C ++代码演示trunc()函数示例

//示例 
// trunc()功能

#include <iostream>
#include <cmath>
using namespace std;

// main()部分
int main(){
    float x;
    
    //输入号码
    cout<<"Enter a float value: ";
    cin>>x;
    
    //四舍五入向零 
    cout<<"trunc("<<x<<"): "<<trunc(x);
    cout<<endl;

    return 0;
}

输出结果

First run:
Enter a float value: 2.3 
trunc(2.3): 2 

Second run:
Enter a float value: 2.5 
trunc(2.5): 2

Third run:
Enter a float value: 2.8 
trunc(2.8): 2 

Fourth run:
Enter a float value: -2.3
trunc(-2.3): -2 

Fifth run:
Enter a float value: -2.5
trunc(-2.5): -2

Sixth run:
Enter a float value: -2.8
trunc(-2.8): -2