#include<stdio.h> #include<stdlib.h> int change_int(int a, int b) //求平均數 { int c = 1, d = 1; c = a&c; //求a的右側第一位,看是否爲奇數, d = b&d; //求b的右側第一位,看是否爲奇數, a >>= 1; b >>= 1; a = a + b; if ((c&d) == 1) //如果兩個數均爲奇數,則補1 a = a + 1; return a; //返回平均數 } int main() { int a,b; printf("please enter a and b:"); scanf("%d%d",&a,&b); //對a,b初始化,即輸入想要求平均數的兩個數 printf("%d\n", change_int(a,b)); //調用函數並輸出 system("pause"); return 0; }
本文只是在下在學習過程自己的想法,只能實現簡單功能,可能還沒考慮到程序的優化,與大神寫出來的代碼還有一定差距,如果那位大神發現了問題,請您不吝賜教,如果您還有更好的方法,不妨分享分享,謝謝!