2014-10-22 43 views
-3

我可以爲C中的變量傳遞多個值嗎?我可以爲C中的變量傳遞多個值嗎?

按照下面的例子,這或多或少是我說的。

int mage;//Normal variable create OK 
int mage{int hp, int mp} 

我現在正在學習C和我想要做一個RPG基於文本的,我不希望創建最好的和最美麗的RPG基於文本的世界,但它只是學習。

如果沒有人在這裏理解我的問題,請使用簡歷:創建一個變量併爲此變量傳遞2個或更多值。

+3

看看'struct'和它做了什麼。 – Ashalynd 2014-10-22 10:56:36

回答

2

是的,C支持允許您定義將其他類型的值組合在一起的新類型的結構。通過使用關鍵字struct並提供名稱來聲明新的結構類型。然後新名稱的名稱是struct

例如:

struct character 
{ 
    int hp; 
    int mp; 
}; 

struct character mage = { 42, 4711 }; 

最後行可創建名爲struct character類型的mage變量,並初始化到mage.hp42mage.mp4711

這裏是你將如何訪問變量mage領域hp

printf("The HP of the mage is %d\n", mage.hp); 
+0

謝謝你的幫助,還有一個問題,如果我想在未來取得這些價值,我的代碼和printf hp的法師和mp我只需要做 printf(mage.mp); //例如?如果我使用像「放鬆」的結構告訴? 也肯定我有更多的結構像字符自定義(名稱,類等..)所以這樣做的法師我繼續像que樣例之前? 結構統計法師{40,100}; struct Character Mage {Name,Gold等等}; – 2014-10-22 12:30:08

+0

@RodolfoOlivieri我添加的代碼更清楚地顯示瞭如何使用點符號打印法師的HP。您評論的其他新問題有點不清楚。你需要閱讀更多關於C的教程類型信息。 – unwind 2014-10-22 12:37:52

+0

是的,我正在學習C,而這正是我想要的,其餘的我可以爲自己做。謝謝。 – 2014-10-22 12:40:33

1

定義爲:

typedef struct { 
int hp; 
int mp; 
} mage; 

用作:

mage m; 

訪問爲:

m.hp = 2; 
m.mp = 3; 
1

如果您想將多個值分組爲單個變量,最簡單的方法是使用struct

這允許您在邏輯上分組值。

在你的榜樣,你可以做這樣的事情:

struct SAttribute { 
    int current; 
    int maximum; 
}; 
typedef struct SAttribute Attribute; 

struct SCharacter { 
    Attribute health; 
    Attribute mana; 
}; 
typedef struct SCharacter Character; 

注意,typedef s爲可選的,只是爲了避免不得不一遍又一遍寫struct

在你實際的程序,你可以使用它們像這樣:

Character mage; 
mage.health.current = mage.health.maximum = 100; 

// damage the mage 
mage.health.current -= 5; 

// is the mage dead? 
if (mage.health.current <= 0) 
    printf("The mage is dead."); 
1

我不知道是否有可能不止一個值傳遞給一個變量,但我會建議你創建一個struct

typedef struct mage mage; 
// define a struct 
struct mage { 
    int hp; 
    int mp; 
}; 

struct mage m = {100, 50}; 

// now we can access the values 
m.hp 
m.mp 
相關問題