数组c比较 [英] C array comparison
本文介绍了数组c比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是比较阵列(C语言)使用的事实上的方法 memcmp
从文件string.h
?
Is the defacto method for comparing arrays (in C) to use memcmp
from string.h
?
我想在我的单元测试来比较整数和双打的阵列
I want to compare arrays of ints and doubles in my unit tests
我不确定是否要使用这样的:
I am unsure whether to use something like:
double a[] = {1.0, 2.0, 3.0};
double b[] = {1.0, 2.0, 3.0};
size_t n = 3;
if (! memcmp(a, b, n * sizeof(double)))
/* arrays equal */
或写一个定制的 is_array_equal(A,B,N)
键入功能?
or to write a bespoke is_array_equal(a, b, n)
type function?
推荐答案
memcmp
会做一个的确切的比较,这是很少一个好主意为花车,也不会按照规则NaN的!= NaN的。对于排序,这很好,但对其他的目的,你可能做一个大致的比较,如:
memcmp
would do an exact comparison, which is seldom a good idea for floats, and would not follow the rule that NaN != NaN. For sorting, that's fine, but for other purposes, you might to do an approximate comparison such as:
bool dbl_array_eq(double const *x, double const *y, size_t n, double eps)
{
for (size_t i=0; i<n; i++)
if (fabs(x[i] - y[i]) > eps)
return false;
return true;
}
这篇关于数组c比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文