为什么*=运算符没有按我期望的方式运行?

Why is the *= operator not functioning the way I would expect it to?

本文关键字:期望 方式 运行 运算符 为什么      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main ()
{
    //If a triangle has a perimeter of 9 units, how many iterations(each iteration is 4/3 as much) would it take to obtain a perimeter of 100 units? (or as close to 100 as you can get?)
    double p = 9; int it = 0;
    for(p; p < 100; p = p * 4/3){
        cout << p << endl;
        it++;
    }
    cout << p << endl;
    cout << it << endl;
    system ("PAUSE");
    return 0;
}

对于我正在做的一个数学项目,我必须计算出如果在每次迭代中将周长增加4/3倍,那么9的周长达到100需要多少次迭代。当我像上面那样编写代码时,输出很好,但是如果我更改

for(p; p < 100; p = p * 4/3)

for(p; p < 100; p *= 4/3)

我得到了没有意义的输出。我是否误解了*=运算符?我需要在某处加括号吗?

这是操作顺序。在p = p * 4/3中,编译器正在做:

p = (p * 4)/3

然而在p *= 4/3中,编译器正在做:

p = p * (4/3)

4/3在计算机上是1,因为是整数除法,所以第二个例子基本上是乘以1。

不是除以3(整数),而是除以3.0(双精度数)或3.0f(浮点数)。那么p *= 4/3.0和p = p * 4/3.0是相同的