我什么时候以及为什么要在c++中使用abs
When and why would i use abs in c++
所以,我看到了一些开源代码,它搜索一组随机的数字,以找到最接近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 )
将为真。
相关文章:
- cpp 使用 abs() 函数和 size_t
- 如何减少 abs 函数的数量
- 无法在 abs 函数 c++ 中使用字符串长度函数
- G++ 错误:重载的"abs(无符号 int)"的调用不明确
- 如何避免 std::abs 的意外结果?
- 用于查找ABS的最小值的算法(A [I] A [J] -K)
- 如何修复"error: call to 'abs' is ambiguous"
- Why is std::abs(9484282305798401ull) = 9484282305798400?
- C++11 exit() 和 abs() 不包括 <cstdlib>?
- 为什么GCC违反了调用ABS功能的代码,并用简短的参数进行功能
- 标准库函数 abs() 在不同C++编译器上的异常行为
- 错误:重载的"abs(double)"调用不明确
- 什么时候会: std::abs(x -y) < std::numeric_limits:<double>:min()
- ABS 函数在 C++ 中没有给出正确的答案
- ABS并使用命名空间性标准
- 在 std::abs 函数上
- ABS与STD :: ABS,参考资料怎么说
- 如何便携式查找min(INT_MAX,abs(INT_min))
- std::abs(0u)是否不规范
- 在C++程序中使用abs()超过时间限制