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

如何将用户输入元素的数组作为判断条件?骰子代码循环异常求助

问题分析与解决方案

首先你的代码陷入死循环的根本原因是:for循环结束后,变量i的值是3,而数组three_num只有3个元素(索引范围0、1、2),访问three_num[3]属于数组越界访问,这是C++中的未定义行为,所以无论输入什么,条件判断的结果都不可控,最终导致循环停不下来。

你不需要在while条件里直接嵌套for循环,有更清晰简便的方法:

方法一:用标志变量判断合法性

在do块内先完成输入,然后遍历数组检查所有元素是否符合要求,用布尔变量标记合法性,最后用这个变量控制循环:

#include <iomanip>
#include <iostream>
using namespace std;

void chose_num(int three_num[])
{
    int i;
    bool is_valid;
    do
    { 
       cout<<"Triple Dice"<<endl<<"Choose 3 numbers between 1 and 6: "<<endl;
       // 输入三个数
       for(i=0;i<3;i++)
       {
           cin>>three_num[i];
       }
       // 校验所有元素合法性
       is_valid = true;
       for(i=0;i<3;i++)
       {
           if(three_num[i] < 1 || three_num[i] >6)
           {
               is_valid = false;
               break; // 只要有一个不合法,直接停止检查
           }
       }
    } while(!is_valid); // 不合法则重新输入
}

int main()
{ 
    int three_num[3];
    chose_num(three_num);

    return 0;
}

方法二:把检查逻辑抽成独立函数

如果后续需要复用校验逻辑,可以把合法性判断写成单独函数,代码可读性和维护性更好:

#include <iomanip>
#include <iostream>
using namespace std;

bool is_all_valid(int arr[], int size)
{
    for(int i=0;i<size;i++)
    {
        if(arr[i] <1 || arr[i]>6)
        {
            return false;
        }
    }
    return true;
}

void chose_num(int three_num[])
{
    int i;
    do
    { 
       cout<<"Triple Dice"<<endl<<"Choose 3 numbers between 1 and 6: "<<endl;
       for(i=0;i<3;i++)
       {
           cin>>three_num[i];
       }
    } while(!is_all_valid(three_num, 3));
}

int main()
{ 
    int three_num[3];
    chose_num(three_num);

    return 0;
}

这两种方法都比在while条件里嵌套for循环更清晰,也更容易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:10:16