編寫一個在輸入 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP