c++絕對(duì)值函數(shù)的用法是什么

c++
小億
168
2024-01-29 15:16:57

C++的絕對(duì)值函數(shù)是用來(lái)計(jì)算一個(gè)數(shù)的絕對(duì)值的函數(shù)。絕對(duì)值是一個(gè)數(shù)的非負(fù)值,如果這個(gè)數(shù)是正數(shù)或零,則它的絕對(duì)值就是它自身;如果這個(gè)數(shù)是負(fù)數(shù),則它的絕對(duì)值是它的相反數(shù)。

C++中有兩個(gè)常用的絕對(duì)值函數(shù):abs()和fabs()。

  1. abs()函數(shù):abs()函數(shù)用于計(jì)算整數(shù)的絕對(duì)值,其函數(shù)原型如下:
int abs(int n);

使用示例:

#include <iostream>
#include <cstdlib>

int main() {
    int num = -10;
    int result = abs(num);
    std::cout << "The absolute value of " << num << " is " << result << std::endl;
    return 0;
}

輸出結(jié)果:

The absolute value of -10 is 10
  1. fabs()函數(shù):fabs()函數(shù)用于計(jì)算浮點(diǎn)數(shù)的絕對(duì)值,其函數(shù)原型如下:
double fabs(double n);

使用示例:

#include <iostream>
#include <cmath>

int main() {
    double num = -10.5;
    double result = fabs(num);
    std::cout << "The absolute value of " << num << " is " << result << std::endl;
    return 0;
}

輸出結(jié)果:

The absolute value of -10.5 is 10.5

需要注意的是,abs()函數(shù)和fabs()函數(shù)需要包含相應(yīng)的頭文件。對(duì)于整數(shù),可以包含頭文件;對(duì)于浮點(diǎn)數(shù),可以包含頭文件。

0