Home > Enterprise >  My output is not accurate in my multiplication game
My output is not accurate in my multiplication game

Time:08-27

So as a project, I'm coding a simple multiplication game in VS Code community 2022, which tells you to enter a number for the multiplication table you want to use, for example the 5 times table and then ask random questions from that times table up to 12x5 in a random order. Here is my code

#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!";
}

}

The output is coming as intended, except for 2 problems. First of all, there is no question asking that number multiplied by 11. Second, the question it asks is some random negative number. Here is a picture of the output Code output

Could someone please give me some tips on how I could solve this

CodePudding user response:

Change

for(int i=1;i<=12;i  )

To

for(int i=0;i<12;i  )

Should resolve your issue. In C an array starts at 0, not 1.

CodePudding user response:

You have an array of 12 elements, which has indices from 0 to 11. In your loop, when you say
i <= 12, you're telling it to go to index 12, which makes it go out of your array. Now because at index 12 you didn't put any value, there's some garbage value residing there. Which is causing the bad calculation.
Your loop should be for (int i = 0; i < 12; i )

  • Related