为什么*=运算符没有按我期望的方式运行?
Why is the *= operator not functioning the way I would expect it to?
#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是相同的
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 创建引用向量的优雅方式
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 不同/较旧的处理器运行c++代码的方式是否不同
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 重载方法的方式会在使用临时调用时生成编译器错误
- 在reactor中存储eventHandlers的最佳方式是什么
- 如何以优化的方式同时迭代两个间距不相等的数组
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 为什么C++有不同的变量初始化方式?
- 使用boost :: Beast进行CPU重的REST API,我是否应该使用异步或同步方式来实现它们以期望延迟
- inotify并没有以我所期望的方式通知我
- 为什么*=运算符没有按我期望的方式运行?