2

I'm having trouble on the last part of my program. The code substracts an array p[j] with an input number nStevilo and then puts in into absolute. It then compares the result with a substraction of an array p[j++]. The code should go through the array and find the smallest value and append it into najblizjeStevilo, but for some reason it doesn't work?

while (j < 20){
        if (abs(p[j] - nStevilo) < abs(p[j++] - nStevilo)){
            najblizjeStevilo = p[j];
        }
    }

The array includes 20 prime numbers, starting from 2 (2, 3, 5, 7, 11...), so p[0] = 2, p[1] = 3...

illia
  • 111
  • 1
  • 8
  • 1
    What does this line means : **"The code should go through the array and find the smallest value and append it into najblizjeStevilo"** . Does it means that you have to sum up all minimum values in each iteration ? – BishalG Nov 26 '18 at 09:25
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read [ask]. Problems like "why doesn't my code work?" must come with a [mcve] and a precise error description. Otherwise they are considered off-topic and usually downvoted and closed. – Ulrich Eckhardt Nov 26 '18 at 09:34

1 Answers1

4

You are relying on sequencing that isn't there. You assume that j will be incremented only after the left hand side of the comparison has finished running. There is no such guarantee by the C++ standard. So your program has undefined behavior on account of modifying j and reading it in one full expression without proper sequencing.

Rather than being clever and writing j++ opt instead to be explicit in how things need to be sequenced:

while (j < 20){
        if (abs(p[j] - nStevilo) < abs(p[j + 1] - nStevilo)){
            ++j;
            najblizjeStevilo = p[j];
        }
    }
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • you are still adding to `najblizjeStevilo` the value of `j + 1`. Not what he was looking for. – Roee Gavirel Nov 26 '18 at 09:29
  • 1
    @RoeeGavirel - He was looking for code that can be reasoned about with well defined semantics. This is leaps and bounds ahead of any "complexed fix" you think you provided. – StoryTeller - Unslander Monica Nov 26 '18 at 09:31
  • Maybe `if (abs(p[j+1] - nStevilo) < abs(p[j] - nStevilo)); ++j;` is what the OP is waiting for. The fact that what OP wants to do is unclear implies that such solutions should be avoided even if it works – Damien Nov 26 '18 at 09:34
  • 1
    @Damien - Writing the increment on the right is a funny way of showing you expect it on the left. I trust Occam's razor enough to pinpoint the apparent fallacy. Now that the OP knows what part of their code had no hope of being well-defined, they can carry on in their journey and figure it if the algorithm is correct to boot. – StoryTeller - Unslander Monica Nov 26 '18 at 09:36