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

C语言彩票抽奖程序输入校验错误提示异常问题求助

C语言彩票程序输入校验问题排查与修复

核心问题分析

你的输入校验模块之所以每次都输出7次重复提示,是因为以下几个逻辑错误:

  • 自身对比导致误判:原代码中用j和k遍历整个数组时,当j == k,必然会触发yours[j] == yours[k]的条件,直接判定为重复。
  • 未处理未初始化的数组元素:数组yours未初始化,未输入的位置是随机垃圾值,会干扰重复判断。
  • 错误处理流程混乱:错误提示后没有重新输入当前错误的数字,而是继续推进循环,导致输入逻辑完全失控。
  • 错误判断顺序不合理:同时存在范围和重复错误时,原代码的判断逻辑无法正确触发复合提示,且break的滥用导致逻辑提前终止。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
    // 初始化随机数种子,避免每次生成相同的彩票序列
    srand((unsigned int)time(NULL));

    int yours[7];
    printf("Buy yours: ");
    
    for (int i = 0; i < 7; ) { // 不自动递增i,错误时重新输入当前数字
        int num;
        // 处理非整数输入的情况
        if (scanf("%d", &num) != 1) {
            printf("Invalid input, please enter an integer.\n\nBuy yours: ");
            // 清空输入缓冲区,避免残留字符影响后续输入
            while (getchar() != '\n');
            continue;
        }

        // 先检查数字范围
        if (num < 1 || num > 45) {
            printf("You cannot choose number out of range from 1 to 45.\n\nBuy yours: ");
            continue;
        }

        // 检查重复:仅与已输入的前i个元素对比
        int is_duplicate = 0;
        for (int j = 0; j < i; j++) {
            if (yours[j] == num) {
                is_duplicate = 1;
                break;
            }
        }

        if (is_duplicate) {
            printf("You cannot choose same number.\n\nBuy yours: ");
            continue;
        }

        // 校验通过,存入数组并推进循环
        yours[i] = num;
        i++;
    }

    printf("Lottery result: ");
    int lottery[7];

    // 生成不重复的彩票号码
    for (int i = 0; i < 7; ) {
        int num = rand() % 45 + 1;
        int is_duplicate = 0;
        for (int j = 0; j < i; j++) {
            if (lottery[j] == num) {
                is_duplicate = 1;
                break;
            }
        }
        if (!is_duplicate) {
            lottery[i] = num;
            i++;
        }
    }

    // 打印彩票号码
    for (int k = 0; k < 7; k++) {
        printf("%d ", lottery[k]);
    }

    // 统计匹配数量
    int match_count = 0;
    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 7; j++) {
            if (lottery[i] == yours[j]) {
                match_count++;
                break; // 找到匹配后跳出内层循环,避免重复计数
            }
        }
    }

    printf("\n");
    printf("The number of matching numbers: %d\n", match_count);

    return 0;
}

关键修改说明

  1. 输入校验逻辑重构:
    • 先将输入存入临时变量num,避免污染数组,同时处理非数字输入的异常情况。
    • 范围检查优先于重复检查,重复检查仅对比已经输入完成的元素,彻底避免自身对比的误判。
    • 使用continue控制循环,只有当输入完全符合要求时,才将数字存入数组并推进循环,确保输入流程正确。
  2. 随机数优化:添加srand初始化种子,解决原程序每次生成相同彩票号码的问题。
  3. 匹配计数优化:找到匹配后立即跳出内层循环,避免同一号码被重复统计,逻辑更严谨。
  4. 修复错误提示逻辑:现在可以分别提示范围错误、重复错误,若输入同时存在两种错误(比如重复的超出范围数字),会先触发范围错误提示,修正范围后再检查重复,符合需求。

内容的提问来源于stack exchange,提问作者Brainfucked

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:55:26