21xrx.com
2025-04-14 23:01:45 Monday
文章检索 我的文章 写文章
C++求多个数的绝对值
2023-07-11 07:28:15 深夜i     21     0
C++ 求值 多个数 绝对值

在C++中,有时需要求多个数的绝对值,本文将介绍两种方法来实现这个过程。

方法一:通过循环求解

这种方法是一种最基本的思路,通过for循环来遍历每一个数,并对每个数求绝对值,最终将结果保存在数组中。下面是使用该方法的代码实现:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
  int n; // 输入的数的个数
  cin >> n;
  int a[n], result[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    result[i] = abs(a[i]);
  }
  for (int i = 0; i < n; i++) {
    cout << result[i] << " ";
  }
  return 0;
}

方法二:使用STL库

这种方法通过调用STL库中的函数来实现,效率较高。使用STL库的方法:

#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
  int n; // 输入数的个数
  // 使用vector动态分配内存
  vector<int> a;
  vector<int> result;
  cin >> n;
  // 读入数据
  for (int i = 0; i < n; i++) {
    int temp;
    cin >> temp;
    a.push_back(temp);
  }
  // 使用transform函数求解绝对值
  transform(a.begin(), a.end(), back_inserter(result), [](int n) {return abs(n);});
  // 输出结果
  for (int i = 0; i < n; i++) {
    cout << result[i] << " ";
  }
  return 0;
}

综上所述,这两种方法都可以实现求多个数的绝对值,其中第二种方法效率较高。但是,在数据量较小的情况下,使用第一种方法也可以满足需求。

  
  

评论区