Whole values in the terminal

-1

I need to sum the odd numbers between 2 values. In online compilers the code works as expected, adding up any odd input values and giving the expected output, but in my terminal (4.15.0-34-generic) when putting, for example, 6 and -5, the output comes out something in around 32655, as if it had reached the limit of int , which I checked on the internet and is not even close to -5 the negative limit of int .

    #include <iostream>

using namespace std;

int main() {

    int x,y,r;
    cin>>x>>y;
    if(x<y) {
        for (x; x<y ; x++){
            if(x%2 == 0) {
                continue;
            }
            else {
                r += x;
            }
        }
        }
    else {
            for (y; y<x ; y++){
                if(y%2 == 0) {
                    continue;
                }
                else {
                    r += y;
                }
        }

    }

    cout<<r<<endl;


    return 0; }

The code is this, it's in C ++.

    
asked by anonymous 04.10.2018 / 12:58

2 answers

1

Probably the problem is that you did not initialize the variable r with 0. So it takes garbage into memory. Because online compilers need controlled environments they have a good chance of having 0 in memory and it works by coincidence. Do not program to run, set to be right. I hope this teaches you that you can not trust the result presented, because it may be just by coincidence. We have many programs running around that "stop working out of nowhere", because the coincidence ceased to exist. to program is not to see if it works, is to prove that it works always, in all situations. Organizing and simplifying the code would look like this:

#include <iostream>
using namespace std;

int main() {
    int x, y, r = 0;
    cin >> x >> y;
    if (x < y) {
        for (; x < y; x++) if (x % 2 != 0) r += x;
    } else {
        for (; y < x; y++) if (y % 2 != 0) r += y;
    }
    cout << r << endl;
}

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

It gives simplification more, but it would probably have a loss of performance, and some would find it less legible.

    
04.10.2018 / 14:01
1

You forgot to initialize r !

So, the value of r is always indeterminate and depends on what you have in memory at the time of your allocation.

Change your startup:

int x,y,r;

in:

int x,y,r=0;
    
04.10.2018 / 13:47