0

I am working on this code (in c++) and I finished but i have 2 errors on line 19 when I use them in for loops about variables y and m, saying that they are uninitialized local variables. I don't see how this is possible because I declared them at the beginning as int and their value is assigned when the user inputs in cin.

#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
#include <vector>

using namespace std;

int main()
{
    int a, b, n, l = 0;

    cin >> a, b, n;

    for (int i = 0; i < 20; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            if (l < (i*a + j*b) && (i*a + j*b) <= n)
                l = i*a + j*b;
        }
    }

    cout << l;

    return 0;
}
e7kim
  • 61
  • 6

2 Answers2

0

I'm not in a position to test this, but Multiple inputs on one line suggests that your syntax should be

cin >> a >> b >> c;

Regardless, I think the compiler is suggesting that assignment to all variables isn't guaranteed by cin so without explicit initialisation when they're declared you're assuming too much.

Community
  • 1
  • 1
christutty
  • 952
  • 5
  • 12
0

Things would have been much better if you had also highlighted the challenge you wanted to solve and the results you intended to achieve. This would have enabled me to guide you more easily.

However, based on your statement and after looking at your lines of code, I spotted a few errors that could possibly lead to such an error.

You have two syntax errors.

  1. C++ does not read the input as cin >> a, b, n;. That's absolutely a syntax error. Instead, it should be: cin>> a >> b >> c;, cin >> a ; cin >> b ; cin >> c;, or:

cin >> a;

cin >> b;

cin >> c;

  1. The if condition in C++ always requires opening and closing curly brackets. Without them, this condition always results in a syntax error.

So, try adding the curly brackets, like this:

if (l < (i*a + j*b) && (i*a + j*b) <= n)
{
   l = i*a + j*b ;
}

The third, but minor, error I spotted in your lines of code that could potentially lead to a logical error lies in the if condition. It is always a good idea to use parentheses in order to facilitate the application of the PEMDAS rule, especially when it comes to calculations.

Therefore, I suggest that you construct your if condition as follows, as this can help reduce logic errors, especially when dealing with complex lines of C++ code:

if (l < ((I*a) + (j*b)) && ((I*a) + (j*b)) <= n))
{
    l = (I*a) + (j*b) ;
}