Skip to content

Latest commit

 

History

History
77 lines (52 loc) · 1.73 KB

File metadata and controls

77 lines (52 loc) · 1.73 KB

C 程序:检查数字是偶数还是奇数

原文: https://www.programiz.com/c-programming/examples/even-odd

在此示例中,您将学习检查用户输入的数字是偶数还是奇数。

要理解此示例,您应该了解以下 C 编程主题:


偶数是可以被 2 整除的整数。例如:0、8、-24

奇数是不能被 2 整除的整数。例如:1、7、-11、15


检查偶数或奇数的程序

#include <stdio.h>
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);

    // True if num is perfectly divisible by 2
    if(num % 2 == 0)
        printf("%d is even.", num);
    else
        printf("%d is odd.", num);

    return 0;
} 

输出

Enter an integer: -7
-7 is odd. 

在程序中,用户输入的整数存储在变量num中。

然后,使用模数%运算符检查num是否能被2完全整除。

如果该数字可以被2完全整除,则测试表达式number%2 == 0的计算结果为1(真)。 这意味着数字是偶数。

但是,如果测试表达式的计算结果为0(假),则该数字为奇数。


使用三元运算符检查奇数或偶数的程序

#include <stdio.h>
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);

    (num % 2 == 0) ? printf("%d is even.", num) : printf("%d is odd.", num);
    return 0;
} 

输出

Enter an integer: 33
33 is odd. 

在上面的程序中,我们使用了三元运算符?:而不是if...else语句。