編寫一個在輸入 1 時返回 2,在輸入 2 時返回 1 的 C 程式設計函式


要編寫一個在輸入 1 時返回 2、在輸入 2 時返回 1 的函式。根據所使用的邏輯,有許多方法可以編寫此函式。最簡單的方法是使用條件語句,即如果數字為 1 則返回 2,否則返回 1,其他方法包括使用數學運算(任何方法都可以)和異或運算。

舉例

#include <stdio.h>
// Method 1 using the if statement
int reverseif(int x) {
   if (x == 1) return 2;
   else return 1;
}
// Method 2 using the subtarction form sum of the two numbers (3 in this case)
int reversesub(int x){
   return (3-x);
}
int main() {
   printf("%d
", reverseif(1));    printf("%d
", reversesub(2));    return 0; }

輸出

2
1

更新於:09-Aug-2019

306 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.