使用C或C++时,如何防止整数溢出
How do I prevent integer overflow when using C or C++?
http://ideone.com/hANuZ
#include <stdio.h>
int main(int argc, char *argv[]) {
/**
* Prints out powers of 2 for 32 iterations.
*/
int iterations = 0;
int value = 1;
while (iterations <= 32) {
// Prints in this format: iterations 2^n value
printf("%dt2^%dt%d", iterations, iterations, value);
switch (iterations) {
case 8:
case 16:
case 32:
printf("tt%d bitn", iterations);
break;
default:
printf("n");
break;
}
value *= 2;
++iterations;
}
return 0;
}
当我编译并运行这段代码时,当我在"value"大于2^30之后打印它时,即使我将其声明为无符号长时,也会发生奇怪的事情。
我该怎么办?我只是个初学者-(
您将其打印为带符号整数。尝试使用格式字符串
"%ut2^%ut%u"
检查您的printf文档中的所有格式化代码及其作用。%u
代表unsigned int
。unsigned long
通常是%lu
简单的答案是尝试将其声明为大于32位的unsigned long long
(根据标准,thx@caf,最小为64位(。
当处理特定大小很重要的类型时,应该使用已知大小的类型,如int64_t
。
只是为了好玩,我确实修改了您的代码示例以提高的清晰度
#include <stdio.h>
int bitcount(unsigned long i) {
int count = 0;
while (i > 0) {
count++;
i>>=1;
}
return count;
}
int main(int argc, char *argv[]) {
/**
* Prints out powers of 2 for 32 iterations.
*/
int iterations = 0;
int value = 1;
while (iterations <= 32) {
// Prints in this format: iterations 2^n value
printf("%dt2^%ut%utt%d bitn", iterations+1, iterations, value, bitcount(value));
value *= 2;
++iterations;
}
return 0;
}
您会注意到127
是8 bit
,256
是9 bit
。这是因为
127 = 1000 0000
256 = 1 0000 0000
此外,2^32
是0
,因为
2^32 = 1 0000 0000 ... 0000 0000 (overflow for int)
= 0000 0000 ... 0000 0000 = 0 (only the first 32 bits are preserved)
如果需要整数精度,则需要使用外部库来获取较大的数字。对于C GMPhttp://gmplib.org/是一个著名的图书馆。如果不需要整数精度,只需使用浮点或双精度。
如果你想知道类型的限制是基于什么,这个页面是可以阅读的http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/CONCEPT/data_types.html.
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 防止主数据类型C++的隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 如何防止双精度值到整数的隐式转换
- 我将如何防止整数在随机发生器中多次生成
- 如何防止在分配整数数组时发生 SIGABRT
- C++ 计算编译时常量,同时防止整数常量溢出
- 防止随机整数不断被重新分配
- 如何防止从字符到整数的隐式转换
- 如果输入了非整数,如何防止无限循环
- 防止使用整数进行自动强制转换
- 在C++中重载运算符时,如何防止整数歧义
- 如何防止整数被分配给字符串
- 在c++中,防止整数0隐式转换为指针的最佳方法是什么?
- 使用C或C++时,如何防止整数溢出
- 防止非整数除法
- 如何防止使用多种整数类型的boost::变体类型的隐式转换
- C++如何防止我的团队开发人员错误地使用整数版本的abs