C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他

绞尽脑汁
srand( 0 );
int points; // number of points
float computerNumber; // number generated by the computer
float guess; // user's guess
char quit; // What the user enters when they want to quit
int totalPoints; //the total score of all of the games played
int avgPoints; // the average score of all games played
int gamesPlayed; // how many games have been played
float rangeLow; // the lower end of the range
float rangeHigh; // the higher end of the range
points = 5;
quit = 'n';
gamesPlayed = 0;
totalPoints = 0;
while ( quit != 'q' )
{

    gamesPlayed++;
    cout << "Welcome to Guessing Game! \n";
    points = 5;
    cout << "What would you like your range to be? \n";
    cout << "Low number: \n";
    cin >> rangeLow;
    cout << "High number: \n";
    cin >> rangeHigh;
    if ( rangeLow > rangeHigh )
    {
        cout << "Please use a high number that is greater than the low number. \n";
        cout << "Low number: \n";
        cin >> rangeLow;
        cout << "High number: \n";
        cin >> rangeHigh;
    }
    else
    {
        ;
    }
    computerNumber = rand( ) % (rangeLow - rangeHigh + 1) + 10;
    cout << "Computer Number: " << computerNumber << endl;
    cout << "Points:" << points << endl;
    cout << "what is your guess? \n" << endl;
    cin >> guess;
    cout << "Your guess is: " << guess << endl;

当我输入此代码(在不影响这些行的其他无错误代码行中)时,它不会编译并输出两条错误消息-“表达式必须具有整数或无作用域的枚举类型”和“'%'是非法,右操作数的类型为“float””

我有一种感觉,这与在我的方程中使用变量有关,但这应该不是问题吗?所有变量类型都是与这个等式有关的浮点数,我很困惑。

泰德·林格莫

%是整数值的模运算符。您的范围端点是浮点变量。在你的练习中,你应该制作端点,computerNumberguess转化为int变量。

int rangeLow, rangeHigh, computerNumber, guess;

然后看看电脑的数字生成器,插入一些值试试看:

computerNumber = rand() % (rangeLow - rangeHigh + 1) + 10;
                 rand() % (   5     -    20     + 1) + 10;
                 rand() %          -14               + 10;

所以,你会有rand() % -14 + 10. 那看起来不正确。反转范围端点:

computerNumber = rand() % (rangeHigh - rangeLow + 1) + 10;
                 rand() % (   20     -    5     + 1) + 10;
                 rand() %            16              + 10;

这, rand() % 16 + 10, 更好,但显然会在范围内创建一个数字[10, 10+16),或者换一种说法(作为闭区间),[10, 25]如果您要更换+10+rangeLow这样的:

computerNumber = rand() % (rangeHigh - rangeLow + 1) + rangeLow;

你现在得到这样的范围:

[rangeLow, rangeLow + rangeHigh - rangeLow + 1)                             =>
[rangeLow, rangeHigh + 1)                          (left-closed interval)   =>
[rangeLow, rangeHigh]                              (closed interval)

这意味着[5, 20]使用我使用的示例值。

现在,看看<随机>。标准库的那部分包含类和函数,使这一切变得更简单:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章