C语言答题统计程序异常:错误答案被计入正确答案数的修正求助
Fix for Correct/Wrong Answer Counting in C Quiz Program
The core issues in your code are:
- The condition
if ('B')is always true (non-zero values are truthy in C, and 'B' has an ASCII value of 66), socorrectAnswerincrements regardless of user input. - Post-increment operators (
correctAnswer++,wrongAnswer++) in the final printf calls modify counters after printing, which is unintended.
Here's the corrected code with proper counting logic:
#include<stdio.h> int main(void) { char choice; int correctAnswer = 0, wrongAnswer = 0; printf("Who developed C?\n"); printf("A. Dennis Leary \tC. Dennis Rodman\n"); printf("B. Dennis Ritchie \tD. Dennis Ruth\n"); printf("Answer: "); scanf("%c", &choice); switch (choice) { case 'A': printf("Wrong Answer.\n"); wrongAnswer++; break; case 'B': printf("Correct Answer.\n"); correctAnswer++; break; case 'C': printf("Wrong Answer.\n"); wrongAnswer++; break; case 'D': printf("Wrong Answer.\n"); wrongAnswer++; break; default: printf("Invalid Answer\n"); wrongAnswer++; // Count invalid inputs as wrong answers } printf("Number of Correct Answers: %d\n", correctAnswer); printf("Number of Wrong Answers: %d\n", wrongAnswer); return 0; }
Key changes:
- Moved counter increments directly into switch cases: increment
correctAnsweronly for 'B', andwrongAnswerfor all other valid options and invalid inputs. - Removed the broken
if-elseblock that incorrectly incrementedcorrectAnswerevery time. - Fixed printf statements to print counter values without modifying them (removed
++operators). - Added proper newline characters (
\n) for cleaner output. - Added
return 0;to comply with C standards for themainfunction.
Alternative fix using if-else (if you want to keep this structure):
Replace the broken block with:
if (choice == 'B') correctAnswer++; else wrongAnswer++;
This correctly checks if the user's choice matches the correct answer before incrementing the appropriate counter.
内容的提问来源于stack exchange,提问作者DumpedBrain
相关产品推荐
相关产品推荐

