-9
因此,我在寻找一些开源代码,它通过随机数字搜索来找到最接近0的数字。由于某种原因,它在库中使用了abs ,我想知道为什么以及在何处使用它。这是代码。什么时候和为什么我会在C++中使用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;
}
我从codec得到了这个代码,我从Bob找到了这个用户。 P.S我很年轻,所以你可以让我更容易理解,请和谢谢。
您是否尝试阅读[abs()](http://www.cplusplus.com/reference/cstdlib/abs/)的文档以查看它的作用? –
与任何其他功能一样,您在需要其提供的功能时使用该功能,并且永远不会有其他功能。 –
什么时候想获得绝对值? –