You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言答题统计程序异常:错误答案被计入正确答案数的修正求助

Fix for Correct/Wrong Answer Counting in C Quiz Program

The core issues in your code are:

  1. The condition if ('B') is always true (non-zero values are truthy in C, and 'B' has an ASCII value of 66), so correctAnswer increments regardless of user input.
  2. 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 correctAnswer only for 'B', and wrongAnswer for all other valid options and invalid inputs.
  • Removed the broken if-else block that incorrectly incremented correctAnswer every 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 the main function.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:55:12