gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:54:37 26 4
gpt4 key购买 nike

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com