ปัญหา
วิธีการลงคะแนน นับ และแสดงคะแนนสำหรับผู้สมัครแต่ละคนที่เข้าร่วมการเลือกตั้งโดยใช้ภาษา 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("\n\n ### Please choose your Candidate ####\n\n");
printf("\n 1. %s", CANDIDATE1);
printf("\n 2. %s", CANDIDATE2);
printf("\n 3. %s", CANDIDATE3);
printf("\n4. %s", “None of These");
printf("\nInput your choice (1 - 4) : “);
scanf("%d",&choice);
switch(choice){
case 1: votescount1++; break;
case 2: votescount2++; break;
case 3: votescount3++; break;
default: printf("\n Error: Wrong Choice !! Please retry");
//hold the screen
getchar();
}
printf(“\n thanks for vote !!");
}
void votesCount(){
printf("\n\n ##### Voting Statics ####");
printf("\n %s - %d ", CANDIDATE1, votescount1);
printf("\n %s - %d ", CANDIDATE2, votescount2);
printf("\n %s - %d ", CANDIDATE3, votescount3);
}
int main(){
int i;
int choice;
do{
printf("\n\n ###### Welcome to Election/Voting 2019 #####");
printf("\n\n 1. Cast the Vote");
printf("\n 2. Find Vote Count");
printf("\n 0. Exit");
printf("\n Please enter your choice : ");
scanf("%d", &choice);
switch(choice){
case 1: castvote();break;
case 2: votesCount();break;
default: printf("\n 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 :