我正在撰寫一個流行病模擬作為學習 C 的一種方式,并且我正在嘗試使用一個名為 Person 的結構來組織我在單個專案下的所有資料。當我嘗試檢查結構的一個值是否大于 100 然后為另一個屬性分配一個值時,我的問題就出現了。
這是我正在使用的結構:
struct Person {
double levelOfInfection;
int cleared;
};
這是未按預期作業的代碼。
void checkForClearance(struct Person targetPerson) {
double val = (double)targetPerson.levelOfInfection - 100.0; // checking if the level of infection is over 100
printf("%f\n",val); // debug print statement
if (val >= 0) { // if over 100 set cleared to 1
targetPerson.cleared = 1;
} else { // if less that 100 set cleared to 0
targetPerson.cleared = 0;
}
}
我的問題是我不明白為 struct 屬性賦值的作用是什么?因為它似乎不像變數那樣作業。如果有人能提供一些關于我寫作時實際發生的事情的見解,targetPerson.cleared = 1;那將是非常有幫助的。
uj5u.com熱心網友回復:
您正在修改結構的副本。您可以通過兩種方式做您想做的事:
---
使用指標(注意->運算子而不是.):
void checkForClearance(struct Person* targetPerson) {
double val = (double)targetPerson->levelOfInfection - 100.0; // checking if the level of infection is over 100
printf("%f\n",val); // debug print statement
if (val >= 0) { // if over 100 set cleared to 1
targetPerson->cleared = 1;
} else { // if less that 100 set cleared to 0
targetPerson->cleared = 0;
}
}
回傳修改后的副本:
struct Person checkForClearance(struct Person targetPerson) {
double val = (double)targetPerson.levelOfInfection - 100.0; // checking if the level of infection is over 100
printf("%f\n",val); // debug print statement
if (val >= 0) { // if over 100 set cleared to 1
targetPerson.cleared = 1;
} else { // if less that 100 set cleared to 0
targetPerson.cleared = 0;
}
return targetPerson;
}
請注意,如果您這樣做,則需要在呼叫后重新分配新值:
person = checkForClearance(person);
uj5u.com熱心網友回復:
像這樣:
void checkForClearance(struct Person *ptargetPerson) {
double val = (double)ptargetPerson->levelOfInfection - 100.0; // checking if the level of infection is over 100
printf("%f\n",val); // debug print statement
if (val >= 0) { // if over 100 set cleared to 1
ptargetPerson->cleared = 1;
} else { // if less that 100 set cleared to 0
ptargetPerson->cleared = 0;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383276.html
下一篇:如何縮短此代碼?-C編程
