开发者

c++ simple function to add numbers

first of all, I just want to say I'm newbie in c++, and I'm tring to solve a problem that I have, but no luck so far. The code is:

const int MAX = 100;

void funkcija(int niz[], int n, int& poc, int& sko)
{
    for(int i = 0; i < n; i++)
    {
        niz[i] = poc + sko;
    }
}

int main()
{
int niz[MAX];
int start, jump;

cout <<"Start element: ";
cin >> start;

cout <<"Jump element: ";
cin >> jump;

funkcija(niz, MAX, start, jump);

cout << "Ispis pocevsi od " << start << " sa skokom od " << jump << " jest: " << niz[1]<< endl;
getchar();
return 0;
}

What the program is supposed to do is: It asks me for 开发者_如何学编程start number. Lets say I pick 15. Then it asks for jump number. I select 11. The print should go "15, 26, 37, 48, 59, 70, 81, 92." (15+11 = 26, 26+11 = 37...) and it should print all numbers until 100, which is my MAX. If I change the MAX to 1000 it should print all numbers until 1000.


You always set the same value in your table elements : poc + sko.

You want to put poc in niz[0] then

for(int i = 1; i < n; i++) {
    nit[i] = niz[i-1] + sko;
}


for(int i = 0; i < n; i++)
{
    niz[i] = poc + sko;
}

You say you want "15+11 = 26, 26+11 = 37...".

Can you think of why this isn't doing that?

For output, you only are outputting a single element from your array (the second element):

<< niz[1]


The problem lies in the for loop. Loop isn't updating the next number in the sequence.

for(int i = 0; i < n; i++)
{
    niz[i] = poc ;
    poc += sko; // This should be added.
}

Also, the condition is wrong. It should be poc < n. Why do you need to pass n, when you have MAX as the global variable.


If I understood correctly that you want 100 numbers, the code should look like this:

void funkcija(int niz[], int n, int poc, int sko)
{
    for(int i = 0; i < n; i++)
    {
        niz[i] = poc;
        poc = poc + sko;
    } 
}

Note that I removed the ampersands (&) from your parameters. Adding these makes them reference parameters, which means after the function returns, the values of start and jump in your main() function are also changed.


Has it occurred to anybody that the third expression in the for loop does not necessarily have to be i++? That particular expression increments i by 1. If you wanted to increment it by some other quantity (e.g., the "jump elemement"), what expression could you use?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜