2016年8月3日 星期三

不用條件敘述判斷奇偶數(Judge a number is even or odd without selection statement)

判斷一整數是否為偶數,若為偶數則輸出1,若否則輸出0
input: 123
output: 0
input: -12
output: 1

直觀法可用if-else判斷:


#include<stdio.h>

void main()
{
    int i = 0, even = 0;
    scanf("%d", &i);
    if (i % 2 == 0)
    {
        even = 1;
    }
    else
    {
        even = 0;
    }
    printf("%d", even);
}
但若明白在C語言中"=="結果的回傳方式,相等則回傳1,不相等則回傳0
(在物件導向語言中,"=="不一定是回傳1和0,例如C#便回傳True和False)
則可使用更簡潔的寫法

#include<stdio.h>

void main()
{
    int i = 0, even = 0;
    scanf("%d", &i);
    even = (i % 2 == 0);
    printf("%d", even);
}

English Version:
There is a request to judge a number is an even or not, output 1 if the inputting is an even, and output 0 if it is odd. For example,
input: 123
output: 0
input: -12
output: 1

It could be solved by using if-else statement intuitively.

#include<stdio.h>

void main()
{
    int i = 0, even = 0;
    scanf("%d", &i);
    if (i % 2 == 0)
    {
        even = 1;
    }
    else
    {
        even = 0;
    }
    printf("%d", even);
}

But how to judge it with basic arithmetic only and no any if-else selection statements ?
In C programming language, the operator "==" returns 1 to means the values on both sides of the "==" operator are equal, and returns 0 means not equal.
So it could be coded as below to get the same result.

#include<stdio.h>

void main()
{
    int i = 0, even = 0;
    scanf("%d", &i);
    even = (i % 2 == 0);
    printf("%d", even);
}

沒有留言:

張貼留言