這樣做:如何檢查int輸入是大於2147436647還是小於-2147483648?
int nbr;
if (nbr <= -2147483648 || nbr >= 2147483647)
printf("No way !!");
不寫沒門!對於低於下限的值(例如-2147483650),因爲輸入數字變爲正數!
這樣做:如何檢查int輸入是大於2147436647還是小於-2147483648?
int nbr;
if (nbr <= -2147483648 || nbr >= 2147483647)
printf("No way !!");
不寫沒門!對於低於下限的值(例如-2147483650),因爲輸入數字變爲正數!
int
只會在超過32位int
的平臺上超出範圍[-2147436647 2147483647]。
#include <limits.h>
int nbr;
#if INT_MIN < -2147483648 || INT_MAX >= 2147483647
if (nbr < -2147483648 || nbr > 2147483647)
printf("No way !!");
#endif
Pre C99平臺可能需要工作來處理-2147483648
。
要檢測一個字符串轉換爲long
將超過其範圍,
char buf[100];
buf[0] = 0;
fgets(buf, sizeof buf, stdin);
errno = 0;
char *endptr;
long x = strtol(buf, &endtr, 10);
if (buf == endptr) puts("No conversion");
else if (errno) puts("Out of long range");
// If `long` is wider than 32-bit and [-2147483648 2147483647] range still needed
else if (x < -2147483648 || x > 2147483647) puts("No way !!");
else printf("%ld\n", x);
使用long long
類型,而不是int
。這將(可能)給你一個64位整數,除非你的編譯器是舊的。如果您使用scanf
,請使用%lld。
最好使用'int64_t',並不是所有的平臺做的事情同樣的方式 –
@MarkYisri注意,雖然'int64_t'極爲普遍實現的 - 和非常有益的,一C99/C11兼容的編譯器不需要提供_optional_類型 - 並不是所有的平臺支持。 (C11 7.20.1.1 3)。所有符合C99/C11的編譯器都提供'long long'。 – chux
你不能看到,如果一個int的範圍之外,因爲它甚至不能保持其範圍之外的值。
你是如何輸入數字的? –
你用什麼函數來輸入?假設一個32位系統,一個'int'不能保存超出該範圍的值。如果您使用其中一個'scanf'函數,則無法檢查數字溢出。 –
使用很長的時間,因爲它確保它可以保持在該範圍之外,請檢查它是否超出Integer的極限,然後將其重新用於計算。 –