我什么时候以及为什么要在c++中使用abs

When and why would i use abs in c++

本文关键字:c++ abs 什么时候 为什么      更新时间:2023-10-16

所以,我看到了一些开源代码,它搜索一组随机的数字,以找到最接近0的数字。出于某种原因,它在库中使用了一些abs,我想知道何时何地使用它。这是代码。

#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
  int N; // the number of temperatures to analyse
  cin >> N; cin.ignore();
  if( N == 0 ) {
        cout << 0 << endl;
        return 0;
    }
    int bestTemp = 5527;
    for( int i = 0; i < N; i++ ) {
        int v;
        cin >> v;
        if( abs( v ) < abs( bestTemp ) ) {
            bestTemp = v;
        } else if( abs( v ) == abs( bestTemp ) && bestTemp < 0 ) {
            bestTemp = v;
        }
    }

    // Write an action using cout. DON'T FORGET THE "<< endl"
    // To debug: cerr << "Debug messages..." << endl;
    cout << bestTemp << endl;
  return 0;
}

我从codingame得到了这个代码,而我发现这个代码的用户是Bob。P.S我还很年轻,你能让我更容易理解吗?谢谢。

abs()给出一个数字的绝对值,这意味着它使负数为正数。

由于abs( v )abs( bestTemp )返回两个数字的正版本,如果v的幅度低于bestTemp(或"接近0"),则abs( v ) < abs( bestTemp )将为真。