1.編寫一個fact函數 #include<stdio.h> #include<stdlib.h> #include<math.h> int fact(int x); int main() { int m, k, p; printf("請輸入m值:"); scanf("%d", &m); printf("請輸入k值:"); scanf("%d", &k); p = fact(m) / (fact(k) * fact(m - k))1.0; printf("p=%d",p); system("pause"); return 0; } int fact(int x) { int number = 1; for (int i = 1; i <=x; i++) { number=inumber; printf("%d\n", number); } return number; } 2.絕對值差函數 #include<stdio.h> #include<stdlib.h> float fun(float x,float y); int main() { float m, n; printf("請輸入兩個值:"); scanf("%f %f", &m ,&n); printf("兩式的差值爲%f", fun(m,n)); system("pause"); return 0; } float fun(float x, float y) { float z; z = x - y; if (x>=y) { z = x - y; } else { z = y - x; } return z; } 3.找出最大值函數並排序 #include<stdio.h> #include<stdlib.h> #include<math.h> #define N 10 void Selection_Sort(int a[],int n); int main() { int a[N]; printf("Enter numbers to sorts:"); for (int i = 0; i < N; i++) { scanf("%d,", &a[i]); } Selection_Sort(a, N); printf("the result is:"); for (int j = 0; j < N; j++) { printf("%d,",a[j]); } system("pause"); return 0; } void Selection_Sort(int a[],int n) { int largest = n - 1, temp; if (n == 1) { return; } if(n>1) { for (int i = 0; i < n; i++) { if (a[i] > a[largest]) { largest = i; } } if (largest < n - 1) { temp = a[n-1]; a[n-1] = a[largest]; a[largest] = temp; } } Selection_Sort(a, n - 1); } 4.普通函數 #include<stdio.h> #include<stdlib.h> #include<math.h> double f(double x); int main() { double x; printf("Enter x:"); scanf("%lf", &x); printf("f(x)=%lf\n", f(x)); system("pause"); return 0; } double f(double x) { return(3 * pow(x, 5) + 2 * pow(x, 4) - 5 * pow(x, 3) - pow(x, 2) - 7 * x - 6); } 5.power函數應用 #include<stdio.h> #include<stdlib.h> #include<math.h> int power2(int x, int n); int main() { double x; printf("Enter x:"); scanf("%lf", &x); printf("f(x)=%lf\n", f(x)); system("pause"); return 0; } int power2(int x,int n) { if (n == 0) return 1; else if (n % 2 == 1) { return x * power2(x, n - 1); } } 6.搖色子 #include<stdio.h> #include<stdlib.h> #include<math.h> #include<time.h> #include<stdbool.h> #include<ctype.h> int roll_dice(); bool play_game(); int main() { int wins = 0, losses = 0; char again; srand(time(NULL)); do { if (play_game()) { printf("you win\n"); wins++; } else { printf("you loss\n"); losses++; } printf("Play again(Y/N)"); scanf("%c", &again); printf("\n"); } while (toupper(again) == 'Y'); printf("Wins:%d Losses:%d\n", wins, losses); system("pause"); return 0; } int roll_dice() { return (rand() % 6 + 1) + (rand() % 6 + 1); } bool play_game() { int roll, point; roll = roll_dice(); printf("you rolled:%d\n", roll); switch (roll) { case 7: case 11: return true; break; case 2: case 3: case 12: return false; break; } point = roll; printf("you rolled:%d\n", point); for (;;) { roll = roll_dice(); printf("you rolled:%d\n", roll); if (roll = point) return true; else if (roll == 7) return false; } }函數