本关任务:有三个候选人,每个选民只能投一票,写一程序,用结构体存储数据,求出得票结果。 三个候选人为"li", "zhang","sun"。
时间: 2023-06-05 11:47:16 浏览: 173
可以这样写代码:struct vote {
char name[10];
int count;
};vote candidate[3] = {{"li", 0}, {"zhang", 0}, {"sun", 0}};int main() {
for (int i = 0; i < 3; i++) {
candidate[i].count++;
}
for (int i = 0; i < 3; i++) {
printf("%s 得票数:%d\n", candidate[i].name, candidate[i].count);
}
return 0;
}
我能为您提供以下程序: struct candidate{
char name[20];
int vote;
}; //初始化结构体
candidate candidates[3] = {
{"li", 0},
{"zhang", 0},
{"sun", 0}
}; //投票
for(int i=0; i<1000; i++){
int vote = rand() % 3;
candidates[vote].vote++;
} //计算得票结果
for(int i=0; i<3; i++){
printf("%s:%d票 \n",candidates[i].name, candidates[i].vote);
}\u6b64\u5173\u4efb\u52a1\u9700\u8981\u4e09\u4e2a\u5019\u9009\u4eba\u7684\u6295\u7968\u6570\u636e\uff0c\u6bcf\u4e2a\u5019\u9009\u4eba\u53ea\u80fd\u6295\u4e00\u7968\u3002\u5e76\u9700\u8981\u5199\u4e00\u4e2a\u7a0b\u5e8f\uff0c\u7528\u7ed3\u6784\u4f53\u5b58\u50a8\u5019\u9009\u4eba\u7684\u6295\u7968\u4fe1\u606f\uff0c\u4ee5\u4fbf\u8fdb\u884c\u4e0b\u4e00\u6b65\u5206\u6790\u3002
\u5982\u679c\u4f7f\u7528 Python \u8bed\u8a00\uff0c\u53ef\u4ee5\u8fd9\u6837\u5199\u4e00\u4e2a\u7a0b\u5e8f\uff1a
```
li_votes = 0
zhang_votes = 0
sun_votes = 0
while True:
vote = input("Please enter your vote (li/zhang/sun): ")
if vote == "li":
li_votes += 1
elif vote == "zhang":
zhang_votes += 1
elif vote == "sun":
sun_votes += 1
else:
print("Invalid vote! Please try again.")
done = input("Are you done voting? (y/n) ")
if done == "y":
break
print("li received", li_votes, "votes.")
print("zhang received", zhang_votes, "votes.")
print("sun received", sun_votes, "votes.")
```
\u8fd9\u4e2a\u7a0b\u5e8f\u5148\u5bf9\u4e09\u4e2a\u5019\u9009\u4eba\u7684\u6295\u7968\u6570\u91cf\u53d6\u5217\u3002\u8f93\u5165\u6570\u636e\u7684\u65f6\u5019\uff0c\u7a0d\u540e\u5bf9\u8f93\u5165\u7684\u5019\u9009\u4eba\u8fdb\u884c\u5206\u6790\uff0c\u5e76\u5c06\u6bcf\u4e2a\u5019\u9009\u4eba\u7684\u6295\u7968\u6570\u91cf\u7ed3\u679c\u8bb0\u5f55\u5230\u76f8\u5e94\u7684\u53d8\u91cf\u4e2d\u3002\u6700\u540e\u63d0\u4f9b\u4e09\u4e2a\u5019\u9009\u4eba\u7684\u6295\u7968\u6570\u91cf\u3002
阅读全文