8.1
#define diff(x, y) ((x) - (y))
8.2
#define max(max(a, b), max(c, d)) ((max(a, b) > max(c, d)) ? (max(a, b)) : (max(c, d)))
#define max(max(max(a, b), c), d) ((max(max(a, b), c) > d) ? (max(max(a, b), c)) : (d))
8.3
#define swap(type, a, b) (int temp; temp = x; x = y; y = temp)
8.4
#include
#define NUMBER 5
void bsort(int a[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = n - 1; j > i; j--)
{
if (a[j] > a[j - 1])
{
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
}
int main(void)
{
int i;
int height[NUMBER];
printf("请输入%d人的身高。\n", NUMBER);
for (i = 0; i < NUMBER; i++)
{
printf("%2d号: ", i + 1);
scanf("%d", &height[i]);
}
bsort(height, NUMBER);
puts("按降序排列。");
for (i = 0; i < NUMBER; i++)
{
printf("%2d号: %d\n", i + 1, height[i]);
}
return 0;
}
8.5
enum sex {man, woman};
enum time {spring, summer, autumn, winter};
8.6
#include
int main(void)
{
int i, num;
int sum = 1;
printf("请输入一个整数: ");
scanf("%d", &num);
if (num > 0)
{
for (i = 1; i <= num; i++)
{
sum *= i;
}
}
printf("%d的阶乘为%d。\n", num, sum);
return 0;
}
8.7
#include
int combination(int n, int r)
{
int c;
if (r ==0 || n == r)
c = 1;
else if (r == 1)
c = n;
else
c = combination(n - 1, r - 1) + combination(n - 1, r);
return c;
}
int main(void)
{
int n, r;
printf("请输入所有不同的整数个数: ");
scanf("%d", &n);
printf("请输入取出的整数个数: ");
scanf("%d", &r);
printf("从%d个不同整数中取出%d个整数的组合数为%d。\n", n, r, combination(n, r));
return 0;
}
8.8
#include
int gcd(int x, int y)
{
int z;
if (x != y)
{
if (x > y)
x -= y;
else
y -= x;
z = gcd(x, y);
}
else
z = x;
return z;
}
int main(void)
{
int x, y;
printf("请输入2个整数的值。\n");
printf("1号: "); scanf("%d", &x);
printf("2号: "); scanf("%d", &y);
printf("2个整数的最大公约数为%d。", gcd(x, y));
return 0;
}
8.9
#include
int main(void)
{
int c, n1;
n1 = 0;
while ((c = getchar()) != EOF)
{
if (c == '\n')
++n1;
}
printf("该标准输入的行数为%d。\n", n1);
return 0;
}
8.10
#include
int main(void)
{
int i, ch;
int cnt[10] = {0};
while ((ch = getchar()) != EOF)
{
if (ch >= '0' && ch <= '9')
cnt[ch - '0']++;
}
puts("数字字符的出现次数。");
for (i = 0; i < 10; i++)
{
printf("'%d': ", i);
while (cnt[i]--)
putchar('*');
putchar('\n');
}
return 0;
}