2-1 水仙花数,输出100~999中所有水仙花数
#include <iostream> using namespace std; int main (void) { for (int i= 100; i <= 999; i++) { int a = i / 100; int b = ( i % 100 ) / 10; int c = i % 10; if ( i == a * a * a + b * b * b + c * c *c ){ cout << i << ' '; } } }
2-3 倒三角形 (提示:把图在纸上画出来,数一数几个星号,几个空,找规律
发现对于n层的倒三角形,第i行,有i-1个空格,有2 * n -2 * i + 1个星号即2(n-i)+1
#include <iostream> using namespace std; int main(void) { int n; cin >> n; for ( int i = 1; i <= n; i++) { for ( int o = 1 ; o < i; o++ ) { cout << ' '; } for (int x = 1; x <= 2 * ( n -i ) + 1; x++) { cout << '*'; } cout << endl; } }
2-4 子序列的和
#include int main (void) { int a, b; float sum=0; while(1){ printf("Please input two numbers\n"); scanf("%d %d", &a, &b); if (a==0 && b==0){ return 0; } if (a >= b || b >= 10e6){ printf("error\n"); continue; } else { for (int i=a; i <= b; i++){ sum+= (1.0/i) * (1.0/i); } printf("%.5f\n", sum); } } }
2-5 分数化小数
#include <stdio.h> int main (void) { while(1){ int a, b, c; scanf("%d %d %d", &a, &b, &c); if (a == b == c == 0) break; printf("%.*f", c, (float) a/b); } }
2-6排列 (提示,用枚举法。因为三个数字各位的和为定值,乘积也为定值,从123扫描到987 / 3,发现满足上述条件的数字即可)
#include <iostream> using namespace std; int calc (int num, int &result_add, int &result_mul) { int i = num / 100; int j = (num % 100) / 10; int k = num % 10; result_add = result_add + i + j + k; result_mul = result_mul * i * j * k; } int main (void) { int i, j, k; int result_add; int result_mul; int sum = 0, pro = 1; for (int a = 1; a <= 9; a++) sum += a, pro *= a; for ( i = 123; i <= 987 / 3; i++ ){ j = i * 2; k = i * 3; result_add = 0; result_mul = 1; calc(i, result_add, result_mul); calc(j, result_add, result_mul); calc(k, result_add, result_mul); if ( result_add == sum && result_mul == pro ){ cout << i << ' ' << j << ' ' << k << endl; } } }