测试高数在C中是奇数还是偶数
我试图测试一个数字是偶数还是奇数。
它适用于 8 位数字,但当我超过 9 位数字时,它看起来很奇怪。我输入的数字发生了变化。
8位数字示例:
Enter the ID : 20202020
20202020 is even.
Program ended with exit code: 0
但是当用 10 位数字做它时,它看起来像这样:
Enter an integer: 2345678915
-1949288381 is odd.
Program ended with exit code: 0
// these nr that are different, what are they?
//Have not found any info about it either...
代码:
#include <stdio.h>
int main()
{
int id;
printf("Enter the Id: ");
scanf("%d", &id);
if(id % 2 == 0)
printf("%d is even.n", id);
else
printf("%d is odd.n", id);
return 0;
}
我试着把它改成双倍,没有帮助。
它与if语句有什么关系吗?
if(id % 2 == 0)
回答
问题不在于模运算,而在于您使用的数据类型。
您的 id 号是一个int,它(在这种情况下)由 32 位组成。这意味着您可以使用的最大数字是2,147,483,647,并且您正在使用更大的数字。
您应该尝试使用long,或使用超过 32 位的数字类型,例如long long. 这意味着您可以使用的最大数量是,解决您的问题。263 - 1 = 9,223,372,036,854,775,807
因此,您应该在代码中进行这些更改:
long long id;
printf("Enter the Id: ");
scanf("%lld", &id);
此页面很好地解释了 C++ 中可用的类型。
- "which, ***in your implementation,*** is formed with 32 bit" 🙂 This is not a requirement of C itself, which only specifies lower limits for ranges for data types, not upper limits.