- 要求显示以下图形
987654321
*87654321
**7654321
***654321
****54321
*****4321
******321
*******21
********1
int main() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < i; j++) {
printf("*");
}
for (int j = 9 - i; j > 0; j--) {
printf("%d", j);
}
printf("\n");
}
}
- 打印斐波那契数列的前三十个数中所有的质数,并统计个数。
bool is_prime(int n) {
if (n <= 1) {
return false;
}
int sqr = sqrt(1.0 * n);
for (int i = 2; i <= sqr; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
int main() {
int ans[30], count = 0;
for (int i = 0; i < 30; i++) {
ans[i] = fib(i+1);
}
printf("质数如下:\n");
for (int i = 0; i < 30; i++) {
if (is_prime(ans[i])) {
printf("%d\n ", ans[i]);
count++;
}
}
printf("Total number is %d.\n", count);
return 0;
}
- 袋子里有2红3绿5黄球,随机从中摸出8个,打印显示所有组合。
int main() {
for (int i = 0; i <= 2; i++) {
for (int j = 0; j <= 3; j++) {
int k = 8 - i - j;
if (k <= 5) {
printf("%d个红球, %d个绿球, %d个黄球。\n", i, j, k);
} else {
continue;
}
}
}
return 0;
}
- 输入n(1-10之间数字),将数字分解显示,如6可以显示为6,5+1,4+2,4+1+1.....
int stack[10];
void divide(int n, int m, int index) {
if (n == 0) {
//当符合条件时,输出
for (int i = 0; i < index - 1; i++) {
printf("%d + ", stack[i]);
}
printf("%d\n", stack[index - 1]);
}
for (int j = n; j > 0; j--) {
if (j <= m) {
stack[index] = j;
divide(n - j, j, index + 1);
}
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
divide(n, n, 0);
}
return 0;
}
- 将十进制ip转换为二进制显示。如输入128.1.2.128,转换为10000000.00000001.00000010.10000000
void change(int n) {
int ans[8] = {0}, flag = 0;
while (n > 0) {
ans[flag] = n % 2;
n = n / 2;
flag++;
}
for (int i = 7; i >= 0; i--) {
printf("%d", ans[i]);
}
}
int main() {
char str[100];
int j, sum = 0;
while(gets(str)) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= '0' && str[i] <= '9') {
j = str[i] - '0';
sum = sum * 10 + j;
} else {
change(sum);
printf(".");
sum = 0;
}
if (i == len - 1) {
change(sum);
}
}
printf("\n");
}
return 0;
}