-
输入两个正整数m和n,求其最大公约数和最小公倍数
#include <stdio.h> int main() { int m, n, c, t, o; printf("请输入两个正整数:\n"); scanf("%d%d", &m, &n); if(m < n){ t = m; m = n; n = t; } o = m * n; c = m % n; while (c != 0){ m = n; n = c; c = m % n; } printf("最大公约数为:%d\n", n); printf("最小公倍数为:%d\n", o / n); return 0; }
-
输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数。
#include <stdio.h> int main() { char c; int letters = 0, space = 0, number = 0, other = 0; printf("请输入一行字符:\n"); while ((c = getchar()) != '\n'){ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) letters++; else if (c == ' ') space++; else if (c >= '0' && c <= '9') number++; else other++; } printf("英文字母数量:%d\n空格数量:%d\n数字数量:%d\n其他字符:%d\n", letters, space, number, other); return 0; }
-
求Sn = a + aa + aaa + ··· + aaa···aa的值,其中a是一个数字,n表示a的位数,由键盘输入,比如:2 + 22 + 222 + 2222 + 22222(此时n = 5)。
核心代码为每次在执行for循环的时候,利用表达式temp * 10 + a生成对应的 1位数 2位数 3位数
input : a = 2, n = 5 output: t = 0 * 10 + 2 sum = 2 t = 2 * 10 + 2 sum = 2 + 22 t = 22 * 10 + 2 sum = 2 + 22 + 222 t = 222 * 10 + 2 sum = 2 + 22 + 222 + 2222 t = 2222 * 10 + 2 sum = 2 + 22 + 222 + 2222 + 22222
#include <stdio.h> int main() { int i, a, n, sum = 0, temp = 0; printf("请输入a的值:"); scanf("%d", &a); printf("请输入n的值:"); scanf("%d", &n); for (i = 1; i <= n; i++) { temp = temp * 10 + a; sum = sum + temp; } printf("sum = %d\n", sum); return 0; }