【紫书】第2章 循环结构
//例2-1 aabb 完全平方
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
for (int x = 1; ; x ++ )
{
int n = x * x;
if (n < 1000) continue;
if (n > 9999) break;
int hi = n / 100;
int lo = n % 100;
if (hi / 10 == hi % 10 && lo / 10 == lo % 10) printf("%d ", n);
}
return 0;
}
//例2-2 3n+1问题
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
int cnt = 0;
while(n != 1)
{
cnt ++;
if (n % 2 == 1)
n = 3 * n + 1;
else
n /= 2;
}
printf("%d", cnt);
return 0;
}
//例题2-4
//重定向读写文件
/*
输入一些整数,求出它们的最小值、最大值和平均值(保留3位小数)。
输入保证这些 数都是不超过1000的整数。
*/
#define LOCAL //标准IO 删除此行
#include<stdio.h>
#define INF 1000000000
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
int x, n = 0, min = INF, max = -INF, s = 0;
while(scanf("%d", &x) == 1)//从data.in输入
{
s += x;
if (x < min) min = x;
if (x > max) max = x;
/*
printf("x = %d, min = %d, max = %d\n", x, min, max);
*/
n++;
}
printf("%d %d %.3f\n", min, max, (double)s/n);
return 0;
}
//习题--------------------------------------------
//2-1 水仙花数
#include <iostream>
#include <stdio.h>
#include <math.h>
int main()
{
for (int i = 100; i <= 999; i ++)
{
int a = i / 100;
int b = i / 10 % 10;
int c = i % 10;
if (i == pow(a, 3) + pow(b, 3) + pow(c, 3))
printf("%d\t", i);
}
return 0;
}
//2-2 韩信点兵
#include <iostream>
#include <stdio.h>
int main()
{
int a, b, c, kase = 0;
bool flag = false;
while(scanf("%d%d%d", &a, &b, &c) == 3)
{
flag = false;
kase ++;
for (int i = 10; i <= 100; i ++ )
{
if (i % 3 == a && i % 5 == b && i % 7 == c)
{
printf("Case %d: %d\n",kase, i);
flag = true;
break;
}
}
if (!flag) printf("Case %d: No answer\n", kase);
}
return 0;
}
//2-3 倒三角形
#include <iostream>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= 2 * n - 1; j ++ )
{
if (j < i) printf(" ");
else
if (i + j <= 2 * n) printf("*");
}
printf("\n");
}
return 0;
}
//2-4 子序列的和
#include <iostream>
#include <stdio.h>
int main()
{
double n, m, s = 0;
int kase = 0;
while(scanf("%lf%lf", &n, &m) == 2)
{
s = 0;
kase ++;
if (n == 0 && m == 0) break;
if (n <= m && n)
{
for (; n <= m; n ++ )
{
s += 1 / (n * n);
}
}
printf("Case %d: %.5lf\n", kase, s);
}
return 0;
}
/*
printf("%.*f", str_len, str);
表示指定小数点后输出多少位, str_len是变量
*/
//2-5 分数化小数
#include <iostream>
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, s = 0;
int c;
int kase = 0;
while(scanf("%lf%lf%d", &a, &b, &c) == 3)
{
s = 0;
kase ++;
if (a == 0 && b == 0 && c == 0) break;
if (b) s = a / b;
printf("Case %d: %.*lf\n", kase, c, s);
}
return 0;
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。