2013-08-27 54 views
1

我正在學習c,這是本書'Head First C'中的練習,我的代碼看起來與示例相同,但是我收到了上述錯誤。'無效的操作數到二進制==(有'數量'和'INT')'是什麼意思?

#include <stdio.h> 

typedef enum { 
    COUNT,POUNDS,PINTS 
}unit_of_measure; 

typedef union { 
    short count; 
    float weight; 
    float volume; 
}quantity; 

typedef struct{ 
    const char *name; 
    const char *country; 
    quantity amount; 
    unit_of_measure units; 
}fruit_order; 

void display(fruit_order order) 
{ 
    printf("The order contains "); 

    if(order.amount==PINTS) //ERROR HERE 
     printf("%2.2f pints of %s\n",order.amount.weight, order.name); 

    else if(order.amount==POUNDS){ //ERROR HERE 
      printf("%2.2f lbss of %s\n",order.amount.weight, order.name); 

    else 
      printf("%i %s\n",order.amount.weight, order.name); 

} 

int main() 
{ 
    fruit_order apples = {"apples","Canada", .amount.count=100, COUNT}; 

    fruit_order strawberries = {"strawberries","England", .amount.count=100, PINTS}; 
    fruit_order oj = {"juice","USA", .amount.count=100, PINTS}; 

    display(apples); 
    display(strawberries); 
    display(oj); 
    return 0; 
} 

這個錯誤是什麼意思?

回答

1
void display(fruit_order order) 
{ 
    printf("The order contains "); 

    if(order.units==PINTS) { 
     printf("%2.2f pints of %s\n",order.amount.weight, order.name); 
    } 
    else if(order.units==POUNDS){ 
      printf("%2.2f lbss of %s\n",order.amount.weight, order.name); 
    } 
    else { 
      printf("%i %s\n",order.amount.weight, order.name); 
    } 
} 

unitsunit_of_measure,我們應該使用order.units==PINTS;我建議我們在if聲明中始終使用{}以使代碼更清晰。我只注意到原始代碼缺少括號。

4

你的意思是:

if (order.units == PINTS) 

否則,你試圖比較有union類型的枚舉值。

+0

哈哈感謝。我不敢相信我做到了。 – RapsFan1981

1

它意味着它說。

order.amount是一個數量,這是一個聯盟。你將它與一個枚舉進行比較,這是一個int。你不能那樣做。

看代碼我想你想要的是比較的左側改爲order.units

if(order.units==PINTS) 
相關問題