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

添加system("cls")致C++赛马游戏程序异常,请求排查问题

赛马游戏程序崩溃问题排查

问题描述

我正在学习C++,需完成课程作业赛马游戏。程序逻辑为:打印代表马匹的#,当随机数大于5时移动该符号,等待片刻后清屏并重复流程。但添加system("cls")后程序完全崩溃,附上代码恳请排查问题。

原代码

#include <iostream>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
using namespace std;
void horse(int &p);

int main()
{
    srand((unsigned) time(NULL));

    int p=0;
    do{
    system("cls");
        horse (p);
        Sleep(250);

    }while (p<20);

}
void horse (int &p)
{
    for (int i;i<20;i++)
        if (i==p)
            cout<<"#";
        else
            cout<<"-";
        cout<<endl; 
        if (rand()%11>5)
            p++;
}

问题根源

程序崩溃的核心原因并非system("cls"),而是**horse函数中for循环的变量i未初始化**:

  • 未初始化的i会读取内存中的随机垃圾值,若初始值远小于20,循环会执行异常多次,输出大量字符导致程序假死或出现崩溃假象;若初始值大于等于20,循环直接跳过,马匹符号根本不会显示。
  • 代码中for循环的缩进存在歧义,cout<<endl;和后续的p++逻辑并未被包含在循环内,虽不是崩溃直接原因,但会影响程序逻辑可读性。

修改后的代码

#include <iostream>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
using namespace std;

void horse(int &p);

int main()
{
    srand((unsigned)time(NULL));

    int p = 0;
    do {
        system("cls");
        horse(p);
        Sleep(250);
    } while (p < 20);
}

void horse(int &p)
{
    // 初始化循环变量i为0
    for (int i = 0; i < 20; i++) {
        if (i == p)
            cout << "#";
        else
            cout << "-";
    }
    cout << endl;
    if (rand() % 11 > 5)
        p++;
}

修改说明

  1. 给for循环的变量i添加初始值0,确保循环从第0位开始遍历,正常输出20个字符的赛道。
  2. 给for循环添加大括号,明确包裹循环体逻辑,避免缩进歧义,提升代码可读性。

内容的提问来源于stack exchange,提问作者Mental-Breakdown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:20:33