例1:均分纸牌
int main() { int i, n, s = 0; long v = 0; printf("请输入纸牌堆数:"); scanf("%d", &n); int a[n]; printf("请输入%d堆纸牌各堆数目\n", n); int t; for(t = 0; t < n; t++){ scanf("%d", &a[t]); v = v + a[t]; } printf("各堆纸牌的数量为:\n"); int m; for(m = 0; m < n; m++) printf("%d\t", a[m]); printf("\n"); v = v/n; printf("每堆牌的平均数为%d \n", v); for (i =0; i < n-1; i++){ if(a[i] != v){ t = a[i]; a[i] = v; a[i+1] = a[i+1] + t - v; s++; } } printf("一共移动了%d步。\n",s); printf("现在每堆纸牌数量是:\n"); for(m = 0; m < n; m++) printf("%d\t", a[m]); printf("\n"); system("pause"); return 0; }
例2: 设有n 个正整数,将他们连接成一排,组成一个最大的多位整数。例如:n=3时,3个正整数13, 312, 343,连接成的最大整数为343312213.
#include <stdio.h> #include <stdlib.h> int main() { int i,j,n; char s[20][20] = {"\0"}; char t1[20] = {"\0"}; char t2[20] = {"\0"}; printf("请输入有多少个正整数:"); scanf("%d", &n); for (i=1; i<n+1; i++) scanf("%s", s[i]); // 直接存储为字符串数组 for(j=1; j<= n-1; j++) // 冒泡排序 for(i=1;i<=n-j; i++) { strcpy(t1, s[i]); strcat(t1, s[i+1]); // 把相邻的两个数组分别进行连接 a+b 和 b+a strcpy(t2, s[i+1]); // 操作,并分别存放在 t1 t2 临时数组里 strcat(t2, s[i]); if(strcmp(t1,t2) < 0) { strcpy(t1, s[i+1]); // 如果 a+b < b+a,则交换顺序 strcpy(s[i+1], s[i]); strcpy(s[i], t1); } } printf("\n连接的最大正整数是:"); for (i=1; i<=n; i++) printf("%s", s[i]); printf("\n"); system("pause"); return 0; }