2016-10-27 35 views
-1

我很困惑。C Enum is all Zeroes

#include "stdio.h" 

typedef enum 
{ 
    INTEGER, 
    NUMBER, 
    FLOAT, 
    CHAR, 
    ARRAY, 
    STRING 
} enumType; 

typedef struct intType 
{ 
    enumType type; 
    int width; 
    int value; 
} Integer; 

typedef struct fltType 
{ 
    enumType type; 
    int width; 
    double value; 
} Float; 

Integer make_int(int val) 
{ 
    Integer tmp; 
    tmp.type = INTEGER; 
    tmp.width = 32; 
    tmp.value = val; 
    return tmp; 
} 

int get_int(Integer val) 
{ 
    int tmp = val.value; 
    return tmp; 
} 

Float make_float(double val) 
{ 
    Float tmp; 
    tmp.type = FLOAT; 
    tmp.width = 32; 
    tmp.value = val; 
    return tmp; 
} 

double get_float(Float val) 
{ 
    double tmp = val.value; 
    return tmp; 
} 

int main(void) { 

    Integer i = make_int(42); 
    printf("Type: %d\nWidth: %d\nValue: %d\n", (int)i.type, i.width, get_int(i)); 

    Float f = make_float(42.8); 
    printf("Type: %d\nWidth: %d\nValue: %f\n", (int)i.type, i.width, get_float(f)); 

    return 1; 

} 

這應該輸出六行,其中兩個「類型」不同。 INTUMER和FLOAT來自enumType。

,而不是...

Type: 0 
Width: 32 
Value: 42 
Type: 0 
Width: 32 
Value: 42.800000 

兩者都是0

即使我修改枚舉,所以這兩個數字肯定是不同的,它仍然不能正常工作:

typedef enum 
{ 
    INTEGER = 0, 
    NUMBER, 
    FLOAT = 1, 
    CHAR, 
    ARRAY, 
    STRING 
} enumType; 

我不知道發生了什麼問題。

+1

您打印'i.type'兩次。當然,它們兩次都是零 – ckruczek

+2

仔細檢查您在第二次printf調用中打印的內容。 – Art

+2

這都是因爲你正在使用'i.type'而不是'f.type'來進行第二個'printf()'調用。 – Sergio

回答

1

變化在第二printf

printf("Type: %d\nWidth: %d\nValue: %f\n", (int)i.type, i.width, get_float(f)); 

printf("Type: %d\nWidth: %d\nValue: %f\n", (int)f.type, f.width, get_float(f)); 
+0

*臉掌*謝謝。 – s4b3r6