代码之家  ›  专栏  ›  技术社区  ›  KolacheMaster

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

  •  0
  • KolacheMaster  · 技术社区  · 8 年前

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

    #include<stdio.h>
    #include<math.h>
    #include<string.h>
    #include<stdlib.h>
    int main(){    
        char str[100];
        char buf[100];
    
        double l,m,a,b;
    
        int c,d,t,u,r,q;
        int count =0;
    
        l=59874.141715197809000;
        m=59874.141715197817000;
    
        a= (l - (int)l);
        b= (m -(int)m);
    
        sprintf(str,"%.15f",a);
        sprintf(buf,"%.15f",b);
    
        c = strlen(str);
        d = strlen(buf);
    
        for(t=3;t<c;t++){
            for(u=3;u<d;u++){
                if(str[t]==buf[u]){
                    count++;
                    break;
                }
            }
        }
        printf("matching decimal places = %d \n",count);
        return 0;
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Brandon    8 年前

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

    例如:

    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;
    }
    
        2
  •  -1
  •   Anonymous    8 年前

    这可能不是答案,但确实如此

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