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'“]
我感觉这与在方程式中使用变量有关,但这不应该成为问题吗?所有与该方程式有关的变量类型都是浮点型,我很困惑。
因此,错误是%
运算符不能与浮点值一起使用,它只能与integer(int
)数据类型一起使用。
您需要将float
转换为int
,一种方法是使用static_cast<int>(yourFloatNumber)
,以便您的计算代码行如下所示:
computerNumber = rand( ) % (static_cast<int>(rangeLow) - static_cast<int>(rangeHigh + 1)) + 10;
模数运算符(%)的要求更为严格,因为操作数必须是整数类型。