|
for (i = 0; i < len - i - 1; i++)也可以写成 for (i = 0; i < len / 2; i++)
|
|
【选择法排序字符串】 #include <stdio.h> #include <string.h>
#define N 10
int main() { char strs[N][100]; char *sorted[N], *temp; // 注意,这里的temp是char *型,不再是int类型了 int i, j, max_j; for (i = 0; i < N; i++) { gets(strs[i]); sorted[i] = strs[i]; } for (i = 0; i < N - 1; i++) { max_j = i + 1; for (j = i + 2; j < N; j++) if (strcmp(sorted[max_j], sorted[j]) > 0) //// 这两个运算符决定是升序还是降序排列 max_j = j; if (strcmp(sorted[i], sorted[max_j]) > 0) /// { temp = sorted[i]; sorted[i] = sorted[max_j]; sorted[max_j] = temp; } } puts("\nResult: "); // 用了puts的话末尾就不要加\n for (i = 0; i < N; i++) puts(sorted[i]); return 0; }
|
|
#include <stdio.h>
int main() { int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int key, i, len, flag = 0; scanf("%d", &key); len = sizeof(nums) / sizeof(int); for (i = 0; i < len / 2; i++) { if (nums[i] == key || nums[len - i - 1] == key) { flag = 1; break; } } if (flag) puts("found"); else puts("not found"); return 0; }
|
|
#include <stdio.h> #define N 50
int main() { char str[N]; char digital[N]; int i; int j = 0; gets(str); for (i = 0; i < N; i++) if (str[i] >= '0' && str[i] <= '9') digital[j++] = str[i]; for (i = 0; i < j; i++) printf("%c ", digital[i]); // 注意这里是digital[i],不是[j],不要写错了 putchar('\0'); return 0; }
|
|
#include <stdio.h> #include <string.h>
int main() { char password[13]; int i, pass = 0; for (i = 0; i < 3; i++) { printf("请输入密码:"); gets(password); if (strcmp(password, "admin") == 0) { pass = 1; break; } } if (!pass) puts("sorry"); return 0; }
|
|
#include <stdio.h> #include <string.h>
int main() { int minlen = -1; int min_i; int i, len; char name[15][20]; for (i = 0; i < 15; i++) { gets(name[i]); len = strlen(name[i]); if (minlen == -1 || minlen > len) { minlen = len; min_i = i; } } printf("名字最短的学生是:%s\n", name[min_i]); return 0; }
|
|
#include <stdio.h>
int main() { int nums[3][4] = {7, 8, 9, 10, 11, 52, 76, 38, 34, 55, 2, 1}; int i, j, r, c, max; max = nums[0][0]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (max < nums[i][j]) { max = nums[i][j]; r = i; c = j; } } } printf("nums[%d][%d] = %d\n", r, c, max); return 0; }
|
|
#include <stdio.h>
int main() { char str[100]; char ch; int i; printf("请输入字符串:"); gets(str); printf("请输入字符:"); ch = getchar(); for (i = 0; str[i] != '\0'; i++) { if (str[i] == ch) break; } if (str[i] != '\0') { for (; str[i + 1] != '\0'; i++) str[i] = str[i + 1]; str[i] = '\0'; } puts(str); return 0; }
|
|
#include <stdio.h>
int main() { int a[4][4] = {{1}, {6, 1}, {8, 7, 1}, {9, 5, 3, 1}}; int i, j; for (i = 0; i <= 2; i++) for (j = 1; j <= 3; j++) a[i][j] = a[j][i]; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) printf("%d ", a[i][j]); putchar('\n'); } return 0; }
|
|
第4章已全部复习完!
|