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


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

該函數將給定值向零舍入,並返回其幅度不大於給定值的最接近的整數值。

例如:

trunc(3.8) = 3;

用法

假設一個數字是 'x'。語法是:

return_type trunc(data_type x);

注意:return_type 可以是 float、double 或 long double。

參數

x: 可以是 float、double 或 long double 的值。

返回值

它返回 x 的舍入值。

例子1

當 x 的值為正時,讓我們看一個簡單的例子。

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float x=8.8;
    std::cout << "The value of x is:" <<x<< std::endl;
    std::cout << "Truncated value of x is:" <<trunc(x)<< std::endl;
    return 0;
}

輸出:

The value of x is:8.8
Truncated value of x is:8

例子2

當 x 的值為負時,讓我們看一個簡單的例子。

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    double x=-3.9;
    std::cout << "The value of x is:" <<x<< std::endl;
    std::cout << "Truncated value of x is:" <<trunc(x)<< std::endl;
    return 0;
}

輸出:

The value of x is:-3.9
Truncated value of x is:-3





相關用法


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