整数溢出的问题

整数溢出问题  。如果整数太打,超出了整数类型的范围会怎么样呢?下面的程序分别从符号类型和无符号类型整数设置为最大允许值加略打一些的值,看结果是什么?

下面一段程序 

#include<stdio.h>
int main(void)
{
 int i=2147483647;
 unsigned int j=4294967295;
 printf("%d/n%d/n%d/n",i,i+1,i+2);
 printf("%u/n%u/n%u/n",j,j+1,j+2);


 return 0;

}

 结果为:

2147483647
-2147483648
-2147483647
4294967295
0
1
-1
0
1
Press any key to continue

无符号整数j象一个汽车里程指示表,当达到最大值的时候,它将溢出到整数点,形成一个循环。整数i也是同样。他们的主要区别是unsigned int 变量j的起点是0,而int的起始点是-2147483648。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,计算阶乘是一个常见的数学运算,特别是当n变得较大,可能会遇到整数溢出问题。为了避免溢出,可以使用迭代或递归的方式,并使用`long long`或者`__int128`这种高精度数据类型。这里提供两种方法: **方法一:迭代计算** ```cpp #include <iostream> using namespace std; // 使用长整型计算阶乘 long long factorial(int n) { long long result = 1; for (int i = 1; i <= n; ++i) { result *= i; // 如果result超过long long的最大值,就不再乘下去 if (result < 0) { throw overflow_error("Factorial overflow"); } } return result; } int main() { int n; cout << "Enter a number: "; cin >> n; try { long long fact = factorial(n); cout << "Factorial of " << n << " is: " << fact << endl; } catch (const overflow_error& e) { cout << "Overflow occurred: " << e.what() << endl; } return 0; } ``` **方法二:使用`std::numeric_limits`检查溢出** ```cpp #include <iostream> #include <limits> using namespace std; // 递归计算阶乘 long long factorial(int n) { if (n < 0) { throw invalid_argument("Negative numbers have no factorial"); } else if (n == 0 || n == 1) { return 1; } else { // 在递归调用前检查可能的溢出 const long long max_value = numeric_limits<long long>::max(); if (n * factorial(n - 1) > max_value) { throw overflow_error("Factorial overflow"); } return n * factorial(n - 1); } } int main() { int n; cout << "Enter a number: "; cin >> n; try { long long fact = factorial(n); cout << "Factorial of " << n << " is: " << fact << endl; } catch (const overflow_error& e) { cout << "Overflow occurred: " << e.what() << endl; } catch (const invalid_argument& e) { cout << "Invalid argument: " << e.what() << endl; } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值