Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math operation in a While

Tags:

c++

c

while-loop

I need solve this operation in a while loop. The N,X, and Z are integers given by the user.

enter image description here

I tried this, but it does not show me the real results.

while (i <= n) {
    double r = 1, p = 1;
    p = x / n + z;
    p = p * p;
    cout << "Resultado: " <<p<< endl;
    i++;           
}
like image 535
Jhonny Afonso Avatar asked Aug 30 '26 22:08

Jhonny Afonso


1 Answers

Your code at least has three issues:

  1. You're re-declaring and re-initializing p every loop iteration, losing the previous value.

  2. You're setting p to x/n+z every iteration, losing the previous value.

  3. Your x/n+z executes the division before the addition.


You're continuously "resetting" p's value here:

while(i <= n)
{
    // ...
    // `p` is getting re-initialized to 1 here:
    // (losing the previous value)
    double r=1, p=1;

    // `p` is being set to `x/n+z` here:
    // (losing the previous value)
    p = x/n+z;

    p = p*p;
    // ...
}

Make a temporary variable instead, and move p's declaration outside the loop:

double p = 1;
while(i <= n)
{
    // ...
    double temp = x/n+z;
    p = p * temp;
    // ...
}

Also, as noted by Daniel S., you require parenthesis around n+z:

double temp0 = x/n+z;
// Evaluates to (x/n)+z.

double temp1 = x/(n+z);
// Evaluates to x/(n+z). (Which is what you want.)

This happens because the / division operator has higher precedence than the + addition operator. Learn about operator precedence here.

like image 164
Vittorio Romeo Avatar answered Sep 02 '26 11:09

Vittorio Romeo