Integer values on the terminal

Asked

Viewed 59 times

-1

I need to sum the odd numbers between two values. In online compilers the code works as predicted, adding 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 result comes out something around 32655, as if it had reached the limit of the int, that I checked on the internet and is not even close to -5 the negative limit of the 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++.

2 answers

1

You forgot to initialize the r!

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

Changes your startup:

int x,y,r;

in:

int x,y,r=0;
  • I ended up discovering this by chance, but thank you so much for sharing the knowledge.

1


Probably the problem is that you didn’t initialize the variable r with a. Then pick up junk in memory. Since online compilers need controlled environments they have a great chance of having 0 in memory and works by coincidence. Don’t program it to work, program it to be right. I hope this will teach him that he cannot trust the result presented, because he may be right just by coincidence. We have many programs running around that "stop working from nothing" by coincidence no longer exist. programming is not to see if it works, it is to prove that it always works, in all situations. Organizing and simplifying the code would be 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You can simplify it more, but you’d probably lose performance, and some would find it less readable.

  • Thank you my noble, this idea of initializing the variable I was completely unaware of.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.