c++在计算算术表达式时溢出

标签 c++

#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << 30000 * (5 * 30000 - 22207) / 2 + 50488389 << std::endl;

    return 0;
}

我要的正确答案是1967383389,但是这个程序在我的电脑上运行后输出-180100259。好像溢出来了。但为什么?如何判断一个算术表达式是否会溢出?

最佳答案

当您编译您的示例代码时,编译器通常会抛出一个警告,准确指出您的表达式溢出的部分

main.cpp:4:24: warning: integer overflow in expression [-Woverflow]
     std::cout << 30000 * (5 * 30000 - 22207) / 2 + 50488389 << std::endl;
                  ~~~~~~^~~~~~~~~~~~~~~~~~~~~

Live Demo


为了克服这个问题,使用所有浮点常量来进行这个计算:

#include <iostream>
#include <cmath>

int main(int argc, char* argv[]) {
    std::cout << std::trunc(30000.0 * (5.0 * 30000.0 - 22207.0) / 2.0 + 50488389.0) << std::endl;
                              // ^^     ^^        ^^        ^^     ^^           ^^

    return 0;
}

Live Demo


How can I judge whether an arithmetic expression will overflow?

您可以查看 std::numeric_limits查看您的编译器实现和 objective-c PU 可用的最大值是多少。


如果您需要问题中提到的精确输出,您可以使用 I/O 操纵器来改变输出的形状:

std::cout  << std::fixed << std::setprecision(0) 
        // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
           << std::trunc(30000.0 * (5.0 * 30000.0 - 22207.0) / 2.0 + 50488389.0) << std::endl;

Live Demo

关于c++在计算算术表达式时溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487616/

相关文章:

c++ - 我怎样才能 cin 和 cout 一些 unicode 文本?

c++ - 分配指向固定大小数组的指针

c++ - 在 printf 之后使用 fflush 会减慢你的程序吗?

c++ - Xerces、xpath 和 XML 命名空间

c++ - ID3D11DeviceContext::DrawIndexed 方法是否等待顶点和像素着色器操作完成?

C++ QThread 和连接导致崩溃

c++ - 私有(private)类的 friend

c++ - 有效地计算两个 std::multimap 迭代器之间的条目数

c++ - 鼠标事件QT

c++ - 在文本文件中查找特定单词?