gpt4 book ai didi

c - 整数溢出以及pow()和乘法的区别

转载 作者:行者123 更新时间:2023-11-30 18:24:46 25 4
gpt4 key购买 nike

当我尝试这个乘法时,编译器给出了整数溢出错误

int main(){
long long int x;
x = 55201 * 55201;
printf("%lld", x);
return 0;
}

但是当我使用 pow() 函数执行相同的操作时,我没有收到任何错误。

int main(){
long long int x;
x = pow(55201, 2);
printf("%lld", x);
return 0;
}

为什么会这样呢?我必须使用第一个代码。

最佳答案

您需要像这样更改代码

int main(){
long long int x;
x = 55201LL * 55201LL; // <--- notice the LL
printf("%lld", x);
return 0;
}

使乘法完成为long long

当您使用 pow 函数时,您不会看到任何问题,因为 pow 使用浮点进行计算。

关于c - 整数溢出以及pow()和乘法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289982/

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