明解C语言 入门篇 第八章答案
作者:互联网
练习8-1
#include<stdio.h> #define diff(x,y)(x-y) int main() { int x; int y; printf("x="); scanf("%d", &x); printf("y="); scanf("%d", &y); printf("%d", diff(x, y)); }
练习8-2
#include <stdio.h> #define max(x,y) ((x)>(y)?x:y) int main() { int a, b, c, d; int max1, max2; printf("请输入a b c d 的值:\n"); scanf("%d",&a); scanf("%d", &b); scanf("%d", &c); scanf("%d", &d); max1 = max(max(a, b), max(c, d)); //这个表达式的意思是先求出a,b一组和c,d一组中的较大值,再比较两个较大值求最大值 printf("最大值是%d", max1); putchar('\n'); max2 = max(max(max(a, b), c), d); //意思是依次比较a和b的较大值,再用较大值依次比较c,d,而求出最大值 printf("最大值是%d", max2); }
练习8-3
#include <stdio.h> #define swap(int,a,b) {int temp;temp = a;x = y;y = temp;} int main(void){ int x = 5; int y = 10; swap(int, x, y); printf("x = %d\ny = %d\n", x, y); return 0; }
练习8-4
#include <stdio.h> #define number 6 void bsort(int n, int v[]) { int i, j; for (i = 0; i < n - 1; i++) { for (j = n - 1; j > i; j--) { if (v[j - 1] < v[j]) { int tem = v[j]; v[j] = v[j - 1]; v[j - 1] = tem; } } } } int main() { int i; int v[number]; for (i = 0; i < number; i++) { printf("v[%d]=", i); scanf("%d", &v[i]); } putchar('\n'); bsort(number, v); for (i = 0; i < number; i++) { printf("v[%d]=%d\n", i, v[i]); } }
练习 8-5
.......
练习8-6
#include <stdio.h> int factorial(int n) { int i ; int sum = 1; for (i = 1; i <= n; i++) { sum*=i; } return sum; } int main() { int x; printf("请输入一个数:"); scanf("%d", &x); printf("它的阶乘是:%d", factorial(x)); }
练习8-7
#include <stdio.h> int factorial(int n) { if (n > 0) return n * factorial(n - 1); else return 1; } int combination(int n, int r) { if (n > 0) return factorial(n) / (factorial(r) * factorial(n - r)); else return 1; } int main() { int n; int r; printf("n="); scanf("%d", &n); printf("r="); scanf("%d", &r); printf("%d", combination(n, r)); }
练习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("x:"); scanf("%d", &x); printf("y:"); scanf("%d", &y); printf("gcd(%d,%d) = %d\n", x, y, gcd(x, y)); return 0; }
练习8-9
/*---计算标准输入中出现的行数---*/ #include <stdio.h> int main(void) { int ch, i = 0; while ((ch = getchar()) != EOF) { if (ch == '\n') i++; } printf("%d", i); return 0; }
练习8-10
#include <stdio.h> int main(void) { int i, ch,j; 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); for (j = 0; j < cnt[i]; j++) { putchar('*'); }putchar('\n'); } return 0; }
标签:main,return,int,scanf,明解,C语言,入门篇,printf,include 来源: https://www.cnblogs.com/nightswatch-candle/p/11890907.html