user1562781
user1562781

Reputation: 379

C++ variables always coming out as zero

I'm running a simple for loop with some if statements. In this for loop, 3 variables are to be given a value depending on the index value in the for loop. It seems fairly simple, however, when I run the code, the values always come out as zero and I have no idea why this is happening. My for loop is provided below. I appreciate any suggestions.

double A [N+1];
double r;
double s;
double v;
for(int i = 2; i < N+1; i++)
{
    if(i == 2)
    {
         r = 1/2/i/(i-1);
         s = -1/2/(i*i - 1);
         v = 1/4/i/(i+1);
    }
    else if(i <= N-2 && i > 2)
    {
        r = 1/4/i/(i-1);
        s = -1/2/(i*i - 1);
        v = 1/4/i/(i+1);
    }
    else if(i <= N-4 && i > N-2)
    {
        r = 1/4/i/(i-1);
        s = 0;
        v = 1/4/i/(i+1);
    }
    else
    {
        r = 1/4/i/(i-1);
        s = 0;
        v = 0;
    }

    A[i] = r*F[i-2] + s*F[i] + v*F[i+2];
    cout << r << s << v << endl;

}

Upvotes: 0

Views: 722

Answers (5)

paxdiablo
paxdiablo

Reputation: 881653

With integers, 1/2 is zero. I would suggest (for a start) changing constants like 2 into 2.0 to ensure they're treated as doubles.

You may also want to (though it may not be necessary) cast all your i variables to floating point values as well, just for completeness, such as:

r = 1.0 / 2.0 / (double)i / ((double)i - 1.0);

The fact that r is a double in no way affects the calculations done on the right of the =. It only affects the final bit (the actual assignment).

Upvotes: 1

sakthisundar
sakthisundar

Reputation: 3288

1/2, 1/4 and -1/2 will always be zero because of the integer division.So try with 1.0/2.0, 1.0/4.0 and -1.0/2.0 to get it sorted out quickly. But follow the basics and do not use many magic numbers inside a code. Consider creating constants for them and use .

Upvotes: 0

Nim
Nim

Reputation: 33655

Three things:

  1. else if(i <= N-4 && i > N-2) makes no sense, that condition cannot hold
  2. all your divisions are integer divisions - to fix, convert one of the numbers to a double.
  3. as a result of 1, when i = N-1, and i = N, then the last branch is taken where you force two variables to 0 anyway!

Upvotes: 4

Paul Mitchell
Paul Mitchell

Reputation: 3281

1, 2 and 4 are integers. In integerland 1/2 = 0 and 1/4 = 0

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545638

It’s happening because you’re using integer division. An example:

r = 1/2/i/(i-1);

This is the same as:

r = ((1 / 2) / i) / (i - 1);

Which is the same as:

r = (0 / i) / (i - 1);

… which is the same as:

r = 0 / (i - 1);

… which is 0.

Because 1 / 2 is 0 in integer arithmetic. To fix this, use floating point values.

Upvotes: 15

Related Questions