我想要一个计算字符R,K,A,T的票数的程序。 当用户键入$时,它将停止程序。
例如,我选择了R。
我不知道为什么它会产生正确的结果减去1而不是正确的结果。有人可以解释一下吗?
代码:
#define TAUB_SYMBOL 'T'
#define KARNIN_SYMBOL 'K'
#define RABANI_SYMBOL 'R'
#define APELOIG_SYMBOL 'A'
#define BLANK_VOTE_SYMBOL 'B'
#define CESSATION_SYMBOL '$'
int main(){
unsigned int countT=0, countR=0, countK=0, countA=0, countBlank=0;
unsigned int num; / /* note that the voter index increases after an invalid votes */
char vote;
unsigned int valid_votes=0;
unsigned int counter=1;
printf("Election Ballot System\n");
printf("----------------------\n");
printf("Ballot secretary, please enter number of registered voters:");
scanf("%d",&num);
printf("Voting now commences.\n");
while(counter<=num){
printf("Voter %u, indicate your vote and press Enter:",counter);
scanf("%c\n", &vote);
if(vote==CESSATION_SYMBOL){
counter=num+1;
}
else{
switch(vote){
case RABANI_SYMBOL:
countR++;
valid_votes++;
break;
case BLANK_VOTE_SYMBOL:
countBlank++;
valid_votes++;
break;
}
counter++;
}
}
printf("Voting is concluded.\n");
printf("Election Results\n");
printf("%d",countR);
return 0;
}
答案 0 :(得分:1)
您需要更改此行
scanf("%c\n", &vote);
收件人
scanf("\n%c", &vote);
自从输入num
之后,您将在每个输入字符(R,K,A,T)之前输入\n
答案 1 :(得分:0)
我有一个解决方案(当然不是最好的):
您可以创建一个新字符,例如char temp
,并用于存储您的"\n"
示例:
scanf("%d%c",&num,&temp);
和
scanf("%c%c", &vote,&temp);