VS Code 2022乘法游戏代码求助:缺11的乘法题及负数异常
乘法游戏程序问题排查与修复
我在VS Code Community 2022中开发了一款简易乘法游戏,功能是输入指定乘法表数字(比如5),随机生成该数字1到12倍的乘法题。但运行时遇到两个问题:
- 从未出现含11的乘法题
- 会随机出现负数题目
原代码如下:
#include<iostream> #include<cstdlib> #include<ctime> #include<random> using namespace std; int main() { int a, ans, points = 0; int x[12] = {1,2,3,4,5,6,7,8,9,10,11,12}; cout << "Welcome to my multiplication game"; cout << "\nEnter the multiplication table you want to play with\n"; cin >> a; random_shuffle(&x[0], &x[11]); for(int i=1;i<=12;i++) { int multiplication = x[i] * a; cout << "What is: " << x[i] << " x " << a << "\n"; cin >> ans; if (ans == a * x[i]) { points++; } } if (points >= 10) { cout << "You have " << points << " points, Well Done!"; } else if (points >= 5 && points <= 9) { cout << "You have " << points << " points, Good try!"; } else { cout << "You have " << points << " points, Better luck next time!"; } }
问题原因分析
1. 未出现11的乘法题
random_shuffle的第二个参数要求是待打乱序列末尾的下一个位置,原代码中&x[11]指向数组第12个元素(值为12)的前一个位置,导致最后一个元素12没被纳入打乱范围;同时数组索引10对应的11虽在打乱范围内,但循环从i=1开始,跳过了索引0的元素,且当i=12时访问的是数组越界位置,根本没遍历到所有12个元素。- 数组x的有效索引是0到11,共12个元素,循环需从i=0开始,到i<12结束,才能遍历全部元素。
2. 出现随机负数题目
当循环执行到i=12时,x[12]属于数组越界访问,该位置的内存是未初始化的垃圾数据,可能是负数,和输入的a相乘后就会出现负数题目。
修复后的代码
#include<iostream> #include<cstdlib> #include<ctime> #include<random> using namespace std; int main() { int a, ans, points = 0; int x[12] = {1,2,3,4,5,6,7,8,9,10,11,12}; cout << "Welcome to my multiplication game"; cout << "\nEnter the multiplication table you want to play with\n"; cin >> a; // 设置随机数种子,保证每次运行打乱结果不同 srand(time(0)); // 修正random_shuffle参数,覆盖全部12个元素 random_shuffle(x, x + 12); // 循环从i=0开始,遍历全部12个元素 for(int i=0;i<12;i++) { int multiplication = x[i] * a; cout << "What is: " << x[i] << " x " << a << "\n"; cin >> ans; if (ans == multiplication) { points++; } } if (points >= 10) { cout << "You have " << points << " points, Well Done!"; } else if (points >= 5 && points <= 9) { cout << "You have " << points << " points, Good try!"; } else { cout << "You have " << points << " points, Better luck next time!"; } return 0; }
内容的提问来源于stack exchange,提问作者MSHypezzz
相关产品推荐
相关产品推荐

