C编程:如何确定2个数字之间的精确匹配

时间:2017-11-01 01:17:31

标签: c arrays matching

我试图找到两个数字之间的完全匹配,并让我的计数器在第一个实例停止时它们不匹配。但是我写的代码计算了我的数字的整个字符串长度。有没有其他方法可以做到这一点?

由于我的计数器是从第一个小数位开始而不是0.,它计为15,但应该停在10。

staging

2 个答案:

答案 0 :(得分:1)

首先,在比较两个字符串时,如果两个字符串的长度不同,则只需要迭代到最小字符串的长度。也就是说,如果要计算字符串中连续字符匹配的数量。 / p>

例如:

A = 0.99997552
B = 0.9999753

需要一个for循环进行比较..你只需迭代到B的长度来确定6个小数匹配。为什么?因为进一步无关是因为B中不存在任何额外的数字。无论如何,迭代超过数组的末尾是未定义的行为。

在你的情况下,两个缓冲区的长度都相同,所以不用担心,但同样,较短的字符串不会在较长的字符串中找到额外的数字。因此:迭代到最小的长度。

解决方案可按如下方式完成:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

int main() {

    //Create large enough buffer to hold 100 digits/characters..
    char str[100] = {0};
    char buf[100] = {0};

    //Two doubles to be compared..
    double l = 59874.141715197809000;
    double m = 59874.141715197817000;

    //Counter keeps track of matching digits..
    int count = 0;

    //Get rid of the base and keep only the decimals..
    double a = (l - (int)l);
    double b = (m - (int)m);

    //Copy a maximum of 15 decimal places to `str` and `buf`
    sprintf(str, "%.15f", a);
    sprintf(buf,"%.15f", b);

    //Get the length of both strings..
    int c = strlen(str);
    int d = strlen(buf);

    //If C is smaller, iterate to length(c) else iterate to length(d).
    for (int i = 2; i < (c < d ? c : d); ++i)
    {
        //If the two characters match, increment the count..
        if (str[i] == buf[i])
        {
            ++count;
        }
    }

    //Print the amount of matching decimals..
    printf("matching decimal places = %d \n", count);
    return 0;
}

答案 1 :(得分:-1)

这可能不是答案,但确实

if (number1 == number2)
{
// do something to stop it
}