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

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++;
}
Your code at least has three issues:
You're re-declaring and re-initializing p every loop iteration, losing the previous value.
You're setting p to x/n+z every iteration, losing the previous value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With