1、练习8-1
#include <stdio.h>
#define diff(x,y) (x-y)
int main ()
{
int a,b;
printf("请输入两个数:"); scanf("%d %d",&a,&b);
printf("两个数的差值为:%d",diff(a,b));
return(0);
}
2、练习8-4
#include <stdio.h>
#define NUMBER 5
void bsort(int a[],int n){
int i, j;
for(i=0;i<n-1;i++){
for(j=0;j<n-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j+1];
a[j+1]=a[j];
a[j]=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;
}
3、练习8-6
#include<stdio.h>
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;
}
4、练习8-8
#include<stdio.h>
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("请输入两个整数的值。\n");
printf("第一个整数: "); scanf("%d", &x);
printf("第二个整数: "); scanf("%d", &y);
printf("两个整数的最大公约数为%d。", gcd(x, y));
return 0;
}
5、练习8-9
#include<stdio.h>
int main(void)
{
int ch;
int n=0;
while((ch=getchar())!=EOF){
if(ch =='\n'){
++n;
}
}
printf("输入的行数为%d。\n",n);
return 0;
}
6、练习8-10
#include<stdio.h>
int main(void)
{
int i, ch;
int cnt[10]={0};
while((ch=getchar())!=EOF){
if(ch >='0'&&ch<='9'){
cnt[ch-'0']++;
}
}
printf("数字字符的出现次数。\n");
for(i=0;i<10;i++){
printf("'%d':",i);
while (cnt[i]>0){
putchar('*');
cnt[i]--;
}
putchar('\n');
}
return 0;
}