C编程——unsigned int溢出问题
C programming - unsigned int overflow problem
我想打印一个整型变量,值为3000000000;
所以我写了下面的代码然后 运行 它,但是打印的值不正确。我认为变量溢出了。但是不知道为什么。
#include<stdio.h>
int main(void) {
unsigned int num1 = 3000000000;
printf("%d", num1);
}
据我所知,无符号整数类型变量的最大值是(2^32-1 = 4,294,967,296 - 1)当代码符合Win32 API.
但是打印出来的值为-1294967296.
我不知道为什么我的代码会发生溢出。
如果有人知道原因,请告诉我:)
此致,
- 我使用的是 Microsoft Visual Studio 2015 Professional。
使用 %u
而不是 %d
对于printf
:
%d
被以下用户使用:
d, i The int argument is converted to signed decimal notation.The
precision, if any, gives the minimum number of digits that
must appear; if the converted value requires fewer digits, it
is padded on the left with zeros. The default precision is 1.
When 0 is printed with an explicit precision 0, the output is
empty.
%u
被以下用户使用:
o, u, x, X
The unsigned int argument is converted to unsigned octal (o),
unsigned decimal (u), or unsigned hexadecimal (x and X) nota‐
tion. The letters abcdef are used for x conversions; the let‐
ters ABCDEF are used for X conversions. The precision, if
any, gives the minimum number of digits that must appear; if
the converted value requires fewer digits, it is padded on the
left with zeros. The default precision is 1. When 0 is
printed with an explicit precision 0, the output is empty.
我想打印一个整型变量,值为3000000000;
所以我写了下面的代码然后 运行 它,但是打印的值不正确。我认为变量溢出了。但是不知道为什么。
#include<stdio.h>
int main(void) {
unsigned int num1 = 3000000000;
printf("%d", num1);
}
据我所知,无符号整数类型变量的最大值是(2^32-1 = 4,294,967,296 - 1)当代码符合Win32 API. 但是打印出来的值为-1294967296.
我不知道为什么我的代码会发生溢出。
如果有人知道原因,请告诉我:)
此致,
- 我使用的是 Microsoft Visual Studio 2015 Professional。
使用 %u
而不是 %d
对于printf
:
%d
被以下用户使用:
d, i The int argument is converted to signed decimal notation.The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.
%u
被以下用户使用:
o, u, x, X The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) nota‐ tion. The letters abcdef are used for x conversions; the let‐ ters ABCDEF are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.