2014-06-15 3 views
0

이것은 CC 모드에서 GCC로 컴파일됩니다.if ((float) (int_one && int_two) == (float) int_one && (float) int_two) 항상 "false"를 계산합니다.

일부 기본 인터프리터 코드를 찾고 있는데이 코드는 "AND"연산자를 구문 분석 할 때 실행됩니다. int_one 기본이와 같이 인수의 정수 값입니다 int_two : 인터프리터의이 부분은 이미 인수 (대신 실수 타입의) 정수 유형은, 왜 우리가 상관 할 것을 결정했습니다

int_one AND int_two 

그들이 실제로 주조 될 때 어떻게 비교 되는가?

나는이 검사가하는 일을 100 % 확신하지 못하고 있으며, 또한 거의 항상 false로 평가하는 이유! 이 수표의 중요성은 무엇이며, 왜 그것이 틀린 이유입니까?

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

int one, two; 
int main() 
{ 

    // Initialize 
    one = 3; 
    two = 3; 

    // do a test with buffering the and result 
    float int_and_cast_to_real = (float)(one && two); 
    float int_cast_to_real_and = (float)one && (float)two; 

    if (int_and_cast_to_real == int_cast_to_real_and) { 
     // This message gets fired, so the buffered results are true. 
     printf("oh they are equal buddy\n"); 
    } else { 
     printf("you think they'd be equal, but they aint.\n"); 
    } 

    // do it all at once 
    if((float)(one && two) == (float)one && (float)two) { 
     printf("int & real ands give equal result\n"); 
    } else { 
     // This message gets fired, so the unbuffered results are false. 
     printf("int & real ands give inequal result\n"); 
    } 


    return 0; 
} 
+4

'&&'는'=='보다 우선 순위가 낮습니다. – Bakuriu

답변

4

예 : 여기

는 다른 결과를 제공되는 결과를 버퍼링에 대한 몇 가지 아마 잘못된 가정을 보여 일부 테스터 코드입니다. 부울 값은 0 또는 1입니다. (one && two);은 부울 1을 반환합니다.이 후 float으로 변환하면 1.000000이되고 (float)one이면 3.000000이 반환됩니다.

그래서, (float)(one && two) == (float)one && (float)two((float)(one && two) == (float)one) && (float)two 마지막 false로 평가 0.000000 == 1.000000을 제공 (때문에 &&보다 == 높은 우선 순위)로 평가됩니다.

+0

답변 해 주셔서 감사합니다! –

1

(float)(one && two) == (float)one && (float)two 조건은 ((float)(one && two) == (float)one) && (float)two으로 평가되지만 귀하의 의도는 (float)(one && two) == ((float)one && (float)two) 인 것으로 보입니다.