21xrx.com
2024-09-20 05:59:57 Friday
登录
文章检索 我的文章 写文章
C++中如何使用abs函数?
2023-06-28 03:33:05 深夜i     --     --
C++ abs函数 使用

C++中的abs()是一个取绝对值的函数,它的使用方式非常简单。abs()函数可用于计算整数、长整数和浮点数类型的绝对值。

在C++中使用abs()函数的方法如下:

对于整数和长整数类型:


#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{

  int a = -100;

  long b = -200;

  int abs_a = abs(a);

  long abs_b = abs(b);

  cout<<"The absolute value of a is "<<abs_a<<endl;

  cout<<"The absolute value of b is "<<abs_b<<endl;

  return 0;

}

运行结果: 

The absolute value of a is 100 

The absolute value of b is 200 

我们声明了两个变量,一个整数类型的a和一个长整数类型的b,并分别为它们计算了绝对值。通过适当的使用命名空间,我们调用了std空间中的abs()函数,并将结果分配给变量abs_a和abs_b。最后,我们输出了变量的值。

对于浮点数类型:


#include <iostream>

#include <cstdlib>

#include <cmath>

using namespace std;

int main()

{

  float c = -45.67;

  double d = -121.75;

  float abs_c = abs(c);

  double abs_d = abs(d);

  cout<<"The absolute value of c is "<<abs_c<<endl;

  cout<<"The absolute value of d is "<<abs_d<<endl;

  return 0;

}

运行结果: 

The absolute value of c is 45.67 

The absolute value of d is 121.75 

在浮点类型中,我们需要包含 头文件并使用std命名空间中的abs()函数。我们声明了一个float型变量c和一个double型变量d,为它们计算了绝对值,并将结果分配给变量abs_c和abs_d。最后我们输出了变量的值。

总的来说,C++语言中的abs()函数是一个非常有用的函数,因为它可以求出整数、长整数和浮点数类型的绝对值。只需要根据变量类型选择合适的类型,即可使用abs()函数,求出绝对值。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复