M00000001
M00000001

Reputation: 309

C++: Pass Two Arrays into A Function But the Results are not Expected by Me

I'm new C++ programmer and just started doing some practice. I came up with the following code but didn't get the result expected by myself(very likely I'm wrong but I cannot make sense of it). I really appreciate your advice on it:

Here is my code:

#include <iostream>

using namespace std;

double simulate(double *p,double *v,double u)
{

    int i = 0;
    while (u>p[i])
    {
        u-=p[i];
        i++;
    }
    cout << v[i];
}
int main()
{
    double array1[] = {0.4,0.1,0.2,0.3};
    double array2[] = {1.1,2.2,3.3,4.4};
    simulate(array1,array2,0.5);
    return 0;
}

The results give 2.2 while I expect 3.3 because: after two loops, u becomes zero so cannot execute the third loop, since we executed two loops, i becomes 2 that corresponds to index 2 in array 2, which is 3.3 instead of 2.2. Could any expert help me with this? Thanks a lot in advance!

Upvotes: 0

Views: 38

Answers (1)

Joseph Larson
Joseph Larson

Reputation: 9078

You're incrementing I within the loop. Think of the logic.

-The while-statement does an if-check. -You then decrement u but increment i. I now points PAST where u becomes <= 0.

This is in addition to the fact you can run off the end of your arrays, if your initial u is too big.

An addition note: please use meaningful variable names. I know this is just a practice, but it's best to get into the right habits from the beginning. Your future coworkers will appreciate it.

Upvotes: 1

Related Questions