strcmp()
我认为是最好的选择,因为它不需要进行任何数字转换。但在这种情况下,您需要确保其中一个存储了仅包含数字字符的字符串。
另外,您可以对该字符串执行 memcmp()
操作。
编辑1
正如其他人指出的有关前导零的问题,您可以手动浏览前导零,并通过传递指向第一个非零数字的指针来调用strcmp()
或memcmp()
。
编辑2
以下代码说明了我的意思。 这仅适用于整数,而不适用于浮点数。
int main (void)
{
char s1[128], s2[128];
char *p1 = s1, *p2 = s2;
while (*p1 && (*p1 == '0'))
p1++;
while (*p2 && (*p2 == '0'))
p2++;
if (strcmp (p1, p2) == 0)
printf ("\nEqual");
else
printf ("\nNot equal");
printf ("\n");
return 0;
}
对于浮点数,小数点后的尾随零应该手动删除。或者整个过程都要手动完成。
编辑4:我还想让您查看此浮点代码。这将检测小数点前导零和小数点后尾随零。例如,00000000000001.10000000000000 和 1.1 将在下面的代码中相等。
int main (void)
{
char s1[128], s2[128];
char *p1, *p2, *p1b, *p2b;
printf ("\nEnter 1: ");
scanf ("%s", s1);
printf ("\nEnter 2: ");
scanf ("%s", s2);
p1 = s1;
p2 = s2;
p1b = s1 + strlen (s1) - 1;
p2b = s2 + strlen (s2) - 1;
while (*p1 && (*p1 == '0'))
p1++;
while (*p2 && (*p2 == '0'))
p2++;
while (((*p1 && *p2) && ((*p1 != '.') && (*p2 != '.'))) && (*p1 == *p2))
{
p1++;
p2++;
}
if ((*p1 == '.') && (*p2 == '.'))
{
while (*p1b == '0')
p1b--;
while (*p2b == '0')
p2b--;
while (((p1 != p1b) && (p2 != p2b)) && (*p1 == *p2))
{
p1++;
p2++;
}
}
if (((*p1 == '\0') && (*p2 == '\0')) || ((p1 == p1b) && (p2 == p2b)))
printf ("\nEqual");
else
printf ("\nNot equal");
printf ("\n");
return 0;
}
在使用前需要进行一些测试。
==
运算符,但没有<
。请给出更多的例子。 - Roland Illig