如何将数组(其元素由用户输入)作为条件?

问题描述 投票:0回答:2
#include <iomanip>
#include <iostream>
using namespace std;

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(three_num[i]<1 || three_num[i]>6);
}

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

    return 0;
} 

我的意思是

while(three_num[i]<1 || three_num[i]>6);
是数组中的每个元素都应该大于1且小于6,如果不是,它循环,我得到的是我输入的任何数字总是循环,我真的应该for循环在 do while 条件下检查所有元素还是有更简单的方法?

c++
2个回答
1
投票

是的,有更好的方法。这是概念代码组织的问题。现在,你有一个令人困惑的结构。如果我为 forloop 添加可选的大括号,我认为它更清楚。

do { 
  cout<<"Triple Dice"<<endl<<"Choose 3 numbers between 1 and 6: "<<endl;
  for(i=0;i<3;i++) {     // NOTE: i used here
    cin>>three_num[i];
  }                      // i is now 3
} while(three_num[i]<1 || three_num[i]>6);  // only checks i=3

请注意,您在 while 条件中实际检查的是

three_num[3]
是否有效。但是
three_num[3]
指向数组中的fourth整数,一些随机字节!这很危险,也是您问题的根源。

在组织上,您可以将代码视为尝试执行以下操作。

// pseudocode
choose_num(three_num[]):
    print message
    while three_num not valid:
        read in three numbers

一个解决方案是编写一个

isValid
函数。例如,

bool isValid(int three_num[]) {
    for (int i = 0; i < 3; i++) {
        if (three_num[i] < 1 || three_num[i] > 6) { return false; }
    }
    return true;
}

然后在上面的伪代码中适当地使用它。

或者,你可以重新排列你的代码看起来像

// pseudocode
choose_num(three_num[]):
    print message
    for i from 0 to 2:
        while num is not valid:
            read in num
        three_num[i] = num

在这种情况下,检查一个数字是否有效可以是一个函数,也可以不是——它非常简短。


如果您有兴趣,我将其他一些程序说明放在这里。这些是您在进一步了解该语言时可以考虑的建议或最佳实践。

three_num[3]
太大时调用
3
的问题是边界检查的问题。在标准库中,
std::vector::at
做一些边界检查。或者通常执行自己的边界检查,以确保不会发生此类问题。

此外,在 OP 中使用

std::endl
会以您不需要和稍微不想要的方式强制流冲洗。
<iomanip>
根本没有使用。


0
投票

你在错误的地方检查条件。您正在等待

for
循环首先完全完成,然后您正在检查超出数组范围的单个值。

在继续读取下一个值之前,您需要重组循环以在从用户读取值的位置执行检查,例如:

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

void chose_num(int three_num[])
{
    bool valid;

    cout << "Triple Dice" << endl;

    do {
        cout << "Choose 3 numbers between 1 and 6: " << endl;
        valid = true;

        for(int i = 0; i < 3; ++i) {
            if (cin >> three_num[i]) {
                if (three_num[i] >= 1 && three_num[i] <= 6) {
                    continue;
                }
            }
            else {
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
            }

            valid = false;
            cout << "Invalid number entered! Try again" << endl;

            break;
        }
    }
    while (!valid);
}

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

    return 0;
} 

或者,将职责分解为更小的功能。你可以有一个只读入一个值的函数,然后有另一个函数来验证该值是否在可接受的范围内,等等。例如:

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

int read_num()
{
    int value;

    while (!(cin >> value)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid number entered! Try again: " << endl;
    }

    return value;
}

int read_num_between(int iMin, int iMax)
{
    int value;

    do {
        value = read_num();
        if (value >= iMin && value <= iMax) {
            break;
        }

        cout << "Number must be between " << iMin << " and " << iMax << "! Try again: " << endl;
    }
    while (true);

    return value;
}

void chose_num(int three_num[])
{
    cout << "Triple Dice" << endl << "Choose 3 numbers between 1 and 6" << endl;
    for(int i = 0; i < 3; ++i) {
        three_num[i] = read_num_between(1, 6);
    }
}

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

    return 0;
} 
© www.soinside.com 2019 - 2024. All rights reserved.