Home  >  Article  >  Backend Development  >  Code to determine odd and even numbers in c language

Code to determine odd and even numbers in c language

下次还敢
下次还敢Original
2024-05-02 15:09:141118browse

在 C 语言中,可使用取模运算(%)判断奇偶数:计算除以 2 后的余数。如果余数为 0,则为偶数;如果余数不为 0,则为奇数。

Code to determine odd and even numbers in c language

如何在 C 语言中判断奇偶数

判断步骤:

判断奇偶数最简单的方法是使用取模运算(%)。

代码片段:

<code class="c">#include <stdio.h>

int main() {
    int number;

    printf("输入一个整数:");
    scanf("%d", &number);

    if (number % 2 == 0) {
        printf("%d 是偶数\n", number);
    } else {
        printf("%d 是奇数\n", number);
    }

    return 0;
}</code>

详细解释:

  • 取模运算 (number % 2):它计算除以 2 后的余数。
  • 如果余数为 0,则表示该数可以被 2 整除,因此是偶数。
  • 如果余数不为 0,则表示该数不能被 2 整除,因此是奇数。

示例用法:

如果输入数字 7,代码将输出:

<code>输入一个整数:7
7 是奇数</code>

The above is the detailed content of Code to determine odd and even numbers in c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn