【问题标题】:Having trouble setting a range a numbers that a user can input无法设置用户可以输入的数字范围
【发布时间】:2016-10-11 18:20:08
【问题描述】:

我正在编写一个程序,除了下面的函数外,一切正常。我很好奇什么是最好的,这样第一个循环的用户输入只能是 1 - 69,而第二个循环只能是 1 - 26。

我打算执行一个 do/while 循环,但出现如下错误。

//***********************************************
//Case 4 lets you input your own lottery numbers*
//***********************************************
void case4()
{
    cout << numberprint << endl;
    tickettop();
    int array_pick[4];
    int pballp;
    for (int i = 0; i < 5; i++)
    {
        cout << evalue << i + 1 << space1;
        do 
       {
        cin >> array_pick[i];
        } while (array_pick > 0 && array_pick <= 69); //Here is where I get an error for array_pick <= 69 (operand types are incompatible ( int * and int))
    }
    for (int i = 0; i < 1; i++)
    {
        cout << eball;
        cin >> pballp;
    }
    cout << endl << endl;
    ofs << endl;
    ticketbottom();
    ofs << bar << box << bar << endl;
}

【问题讨论】:

  • while (!(array_pick &gt; 0 &amp;&amp; array_pick &lt;= 69));,我没有看到你的第二次尝试。

标签: c++ arrays loops


【解决方案1】:
int lottonumber;

ask: //goto label
cin >> lottonumber; //prompt value in console
//if lower than 1 or higher than 69, goto label
if (lottonumber < 1 || lottonumber > 69)goto ask; 

人们不喜欢goto 标签,但在这种情况下它不是问题。 While 循环和 for 循环的存在是为了使代码更易于理解和组织。 goto 标签不会让你的程序变慢或“坏”,它只会让你更难组织。或者在这种情况下,更容易。

【讨论】:

    【解决方案2】:

    您的代码存在许多问题。此行有两个问题:

    } while (array_pick > 0 && array_pick <= 69);
    

    首先,您将数组与整数进行比较,这就是编译器错误的来源。其次,条件应该与现在相反:您希望循环继续直到用户输入正确的值,因此如果输入的值超出范围,而不是实际正确时,您需要条件为真.

    你的意思可能是这样的:

    } while (array_pick[i] < 0 || array_pick[i] > 69);
    

    要检查第二个输入,您可以使用相同的 do...while 构造,只需更改条件:

    cout << eball;
    do 
    {
        cin >> pballp;
    } while (pballp < 0 || pballp > 26);
    

    但据我所知,您的代码还有其他问题,尽管其余部分在语法上是正确的。

    第一个循环将超出array_pick 数组的范围。

    for (int i = 0; i < 5; i++)
    

    i 将采用值 0、1、2、3 和 4,但您在此循环中修改的数组定义为 int array_pick[4],因此只会有带有索引 0、1、2 和 3。

    第二个for 毫无意义,因为循环只会执行一次迭代。

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2017-08-31
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多