我在人脸识别系统中使用了“嵌套的if”语句。显示的代码中的“嵌套”是否正确?

时间:2019-12-01 18:16:55

标签: c face-recognition nested-if

所以问题基本上是我是否正确使用了嵌套的if语句。该代码基本上首先要求用户输入眼睛和鼻子到下巴的距离,然后计算它们的比率。此后,计算每个比率及其可能性之间的差异。一旦计算,if语句将用于确定哪些图像具有最接近的差值,从而将其用于验证站在相机前的人。

#include <stdio.h>
#include <math.h>
int main(void)
{
    /* Declare variables. */
    double eyes_1, eyes_2, eyes_3, nose_chin_1, nose_chin_2,
        nose_chin_3, ratio_1, ratio_2, ratio_3, diff_1_2,
        diff_2_3, diff_1_3;
    /* Get user input from the keyboard. */
    printf("Enter values in cm. \n");
    printf("Enter eye distance and nose-chin distance for image 1: \n");
    scanf_s("%lf %lf", &eyes_1, &nose_chin_1);
    printf("Enter eye distance and nose-chin distance for image 2: \n");
    scanf_s("%lf %lf", &eyes_2, &nose_chin_2);
    printf("Enter eye distance and nose-chin distance for image 3: \n");
    scanf_s("%lf %lf", &eyes_3, &nose_chin_3);
    /* Compute ratios. */
    ratio_1 = eyes_1 / nose_chin_1;
    ratio_2 = eyes_2 / nose_chin_2;
    ratio_3 = eyes_3 / nose_chin_3;
    /* Compute differences. */
    diff_1_2 = fabs(ratio_1 - ratio_2);
    diff_1_3 = fabs(ratio_1 - ratio_3);
    diff_2_3 = fabs(ratio_2 - ratio_3);

    /* Find minimum difference and print image numbers. */
    if (diff_1_2 <= diff_1_3)
    {
        printf("Best match is between images 1 and 2 \n");
        if (diff_1_2 <= diff_2_3)
            printf("Best match is between images 1 and 2 \n");
    }

    if (diff_1_3 <= diff_1_2)
    {
        printf("Best match is between images 1 and 3 \n");
        if (diff_1_3 <= diff_2_3)
        printf("Best match is between images 1 and 3 \n");
    }

    if (diff_2_3 <= diff_1_3)
    {
        printf("Best match is between images 2 and 3 \n");
        if (diff_2_3 <= diff_1_2)
            printf("Best match is between images 2 and 3 \n");
    }

    /* Exit program. */
    return 0;
}

在此算法中,如果语句如下,则嵌​​套的部分:

if (diff_1_2 <= diff_1_3)
    {
        printf("Best match is between images 1 and 2 \n");
        if (diff_1_2 <= diff_2_3)
            printf("Best match is between images 1 and 2 \n");
    }

    if (diff_1_3 <= diff_1_2)
    {
        printf("Best match is between images 1 and 3 \n");
        if (diff_1_3 <= diff_2_3)
        printf("Best match is between images 1 and 3 \n");
    }

    if (diff_2_3 <= diff_1_3)
    {
        printf("Best match is between images 2 and 3 \n");
        if (diff_2_3 <= diff_1_2)
            printf("Best match is between images 2 and 3 \n");
    }

1 个答案:

答案 0 :(得分:0)

这取决于您希望此算法显示的内容。
在此程序中,编译器首先评估外部if语句,如果它是真的,则打印“ x和y之间的最佳匹配”,以获得(x!= y)。然后,它对内部块进行赋值,因为如果是,则再次打印同一行;如果为假,则移至下一个外部if语句。
而如果外部if陈述式为假,它只会继续移至下一个外部if陈述式。
现在,让我们看一下输出的可能性。 如果所有差异(x,y,z)相等,则输出将显示三行有争议的语句的六行,很多人可能会将其视为逻辑错误。
我建议您要做的是在每种情况下都使用逻辑运算符(并停止使用nested-if)。
例如:if (diff_1_2 <= diff_1_3 && diff_1_2 <= diff_2_3)。这样做是为了让程序仅在两个条件都为真时才返回1(或真)。