c++ 如何把数组(其元素是由用户输入的)作为条件?

uinbv5nw  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(187)
#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,如果不是,它会循环,我得到的是我输入的任何数字总是循环,我真的应该在do while条件中循环,以便检查所有元素,或者有更简单的方法吗?

wkyowqbh

wkyowqbh1#

是的,有更好的办法。这是一个概念性代码组织的问题。现在,你有一个令人困惑的结构。如果我为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]指向数组中的第四个整数,一些随机字节!这是危险的,也是问题的根源。
在组织上,您可以将代码视为尝试执行以下内容。

// 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

在这种情况下,检查一个数字是否有效可能是一个函数,也可能不是--它非常简短。
我在这里放了几个其他的程序注解,以防你感兴趣。这些都是建议或最佳实践,您可以在学习更多语言时考虑这些建议或最佳实践。
3太大时调用three_num[3]的问题是边界检查的问题。在标准库中,std::vector::at执行一些边界检查。或者通常执行您自己的边界检查,以确保此类问题不会发生。
此外,在OP中使用std::endl会强制流以一种您不需要的方式刷新。而<iomanip>根本没有使用。

cwdobuhd

cwdobuhd2#

您在错误的位置检查了条件。您首先要等待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;
}

相关问题