C语言 投票问题
問題描述: ? ? ? ? ??
? ? ? ?有N個選民參與投票,候選人分別為A,B,C,D, 現在選民分別投A,B,C,D代表4個候選人(數據由電腦隨機產生),無效數據自動排出;最后由高到低排列候選人和其票數;
要點解決:1. 產生隨機數要用到隨機種子, 以當前時間為起始點進行隨機,生成隨機數較大 對其取余,加上’A‘即可生成對應的ABCDEF.....范圍由余數決定。
? ? ? ? ? ? 2.候選人和其票數的排列問題可以用兩個數組解決,一個數組存取票數,另一個數組存取候選人名稱,兩個對應,對票數進行冒泡排序, 交換數組值的同時把姓名
也進行交換。
代碼 :
#include "stdafx.h" #include "time.h" #include "stdlib.h"int _tmain(int argc, _TCHAR* argv[]) {char name[4] = {'A', 'B', 'C', 'D'};char vote[100] = {'\0'};int n = 0, abandon = 0;int a[4] = {0};scanf("%d", &n);srand((unsigned)time(NULL));//設定隨機種子for(int i = 0; i < n; i++) {vote[i] = rand() % 7 + 'A'; //設定投票的范圍printf("%c", vote[i]);switch (vote[i]) {case 'A':a[0]++;break;case 'B':a[1]++;break;case 'C':a[2]++;break;case 'D':a[3]++;break;default :abandon++;break;}}for(int i = 0; i < 4 - 1; i++) {for(int j = 0; j < 4 - i - 1;j++) {if(a[j] < a[j + 1]) {int temp = a[j];a[j] = a[j + 1];a[j + 1] = temp;char temp1 = name[j];name[j] = name[j + 1];name[j + 1] = temp1;}}}printf("\n");for(int i = 0; i < 4; i++) {printf("%c的票數:%d\n", name[i], a[i]);}printf("棄權的票數:%d\n", abandon);return 0; }總結
- 上一篇: https安全认证流程简介
- 下一篇: 模拟电路64(滤波电路)