在While循环中的数学运算

3

我需要在一个while循环中解决这个操作。用户提供整数NXZ

enter image description here

我尝试过这个,但它并没有显示真正的结果。
while (i <= n) {
    double r = 1, p = 1;
    p = x / n + z;
    p = p * p;
    cout << "Resultado: " <<p<< endl;
    i++;           
}

r 的目的是什么? - Cornstalks
3个回答

3
您的代码至少存在三个问题:
  1. 您在每个循环迭代中重新声明和初始化 p,导致前一个值丢失。

  2. 您在每个迭代中将p设置为x/n+z,导致前一个值丢失。

  3. 您的x/n+z在执行加法之前执行除法。


在此处您不断“重置”p的值:

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;
    // ...
}

可以使用临时变量来替代,然后将 p 的声明移到循环外部:

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

此外,正如Daniel S.所指出的那样,你需要在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.)

这是由于除法运算符 / 的优先级高于加法运算符 +。可以在此处了解运算符优先级

3
请将英语翻译成中文。只返回翻译后的文本:不要忘记在n+z周围加上括号。 - Daniel S.
2
  1. xnz都是int类型,因此除法无法正常工作 - 将x转换为double类型。
  2. 表达式中是否应该包含i?否则你只是计算x / (n + z)i次方。我建议使用p *= (double)x / (i + z)
- Weather Vane

1
一些C++语法错误和一个很好的数学错误。
int i=1; // don't forget the initialization of i
double p = 1/2; // p will be your result, stored outside of the while so we keep memory
while(i<=n) // you want to loop from 1 to n included
{
    // we don't need r
    p = p * x / (n + z); // you forgot the parenthesis here, without them you are doing (x / n) + z;
}

所以一开始 p = 1/2,这是你方程式的左半部分,然后在每个循环中,我们将p的当前值乘以因子x / (n + z)。由于这个因子从一个循环到另一个循环不会改变,所以你也可以将其存储在某个地方。
这应该可以正常工作。

0
double s;
double p = 1;
int n, x, z;
int i = 1;
while (i <= n)
{
    p = p*(x / (n + z));
    i++;
}
s = 1 / 2 * p;

5
请进一步解释。请解释为什么原文作者的代码无法正常工作,以及你的建议是如何解决这个问题的。请用通俗易懂的语言进行翻译,但不要改变原文的意思,也不要提供额外的解释。 - davejal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接