編寫一個 C 程式,使用 Switch case 呼叫函式來選舉候選人
問題
如何使用 C 語言為參加選舉的每位候選人投票、統計和顯示得票數?
解決方案
我們考慮一下三位參加選舉的人。這裡我們需要為以下部分編寫程式碼 -
投票 - 按下投票鍵選擇候選人
查詢得票數 - 查詢每位候選人獲得的總得票數,並宣佈獲勝者。
示例
使用 Switch case 呼叫每個函式來執行所有這些操作 -
#include<stdio.h>
#define CANDIDATE_COUNT
#define CANDIDATE1 "ABC"
#define CANDIDATE2 "XYZ"
#define CANDIDATE3 "PQR"
int votescount1=0, votescount2=0, votescount3=0;
void castvote(){
int choice;
printf("
### Please choose your Candidate ####
");
printf("
1. %s", CANDIDATE1);
printf("
2. %s", CANDIDATE2);
printf("
3. %s", CANDIDATE3);
printf("
4. %s", “None of These");
printf("
Input your choice (1 - 4) : “);
scanf("%d",&choice);
switch(choice){
case 1: votescount1++; break;
case 2: votescount2++; break;
case 3: votescount3++; break;
default: printf("
Error: Wrong Choice !! Please retry");
//hold the screen
getchar();
}
printf(“
thanks for vote !!");
}
void votesCount(){
printf("
##### Voting Statics ####");
printf("
%s - %d ", CANDIDATE1, votescount1);
printf("
%s - %d ", CANDIDATE2, votescount2);
printf("
%s - %d ", CANDIDATE3, votescount3);
}
int main(){
int i;
int choice;
do{
printf("
###### Welcome to Election/Voting 2019 #####");
printf("
1. Cast the Vote");
printf("
2. Find Vote Count");
printf("
0. Exit");
printf("
Please enter your choice : ");
scanf("%d", &choice);
switch(choice){
case 1: castvote();break;
case 2: votesCount();break;
default: printf("
Error: Invalid Choice");
}
}while(choice!=0);
//hold the screen
getchar();
return 0;
}輸出
###### Welcome to Election/Voting 2019 ##### 1. Cast the Vote 2. Find Vote Count 0. Exit Please enter your choice : 1 ### Please choose your Candidate #### 1. ABC 2. XYZ 3. PQR 4. None of These Input your choice (1 - 4) : 1 thanks for vote !! ###### Welcome to Election/Voting 2019 ##### 1. Cast the Vote 2. Find Vote Count 0. Exit Please enter your choice : 1 ### Please choose your Candidate #### 1. ABC 2. XYZ 3. PQR 4. None of These Input your choice (1 - 4) : 1 thanks for vote !! ###### Welcome to Election/Voting 2019 ##### 1. Cast the Vote 2. Find Vote Count 0. Exit Please enter your choice : 2 ##### Voting Statics #### ABC - 2 XYZ - 0 PQR - 0 ###### Welcome to Election/Voting 2019 ##### 1. Cast the Vote 2. Find Vote Count 0. Exit Please enter your choice :
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP