C/C++编程学习 - 第3周 ④ 水仙花数

题目链接

题目描述

春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153 = 13 + 53 + 33

现在要求输出所有在 m 和 n 范围内的水仙花数。

Input
输入数据有多组,每组占一行,包括两个整数 m 和 n (100 <= m <= n <= 999)。

Output
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开;如果给定的范围内不存在水仙花数,则输出no。

每个测试实例的输出占一行。

Sample Input

100 120
300 380

Sample Output

no
370 371

思路

模拟题目的操作即可。根据题目描述,水仙花数是指一个三位数,它的各位数字的立方和等于其本身。

C语言代码:

#include<stdio.h>
#include<math.h>
int check(int i)
{
	int x = i;
	int x1 = x % 10;
	x = x / 10;
	int x2 = x % 10;
	x = x / 10;
	int x3 = x % 10;
	if((x1 * x1 * x1 + x2 * x2 * x2 + x3 * x3 * x3) == i) return 1;
	else return 0;
}
int main()
{
	int m, n;
	while(~scanf("%d %d", &m, &n))
	{
		int flag = 1;
		int cnt = 0;
		for(int i = m; i <= n; i++)
		{
			if(check(i))
			{
				cnt++;
				if(flag)
				{
					flag--;
					printf("%d", i);
				}else printf(" %d", i);
			}
		}
		if(cnt == 0) printf("no\n");
		else printf("\n");
	}
	return 0;
}

C++代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(false);	//加速读入
	int m, n, cnt;
	while(cin >> m >> n)
	{
		cnt = 0;
		for(int i = m; i <= n; i++)
		{
			int a = i / 100;	//百位 
			int b = i / 10 % 10;//十位 
			int c = i % 10;		//个位 
			if(i == a * a * a + b * b * b + c * c * c)
			{
				if(cnt == 0) cout << i;
				else cout << " " << i;
				cnt++;
			}
		}
		if(cnt == 0) cout << "no";
		cout << endl;
	}
	return 0;
}

下面这一句的功能是加速读入数据,不写也行。

ios::sync_with_stdio(false);

其实水仙花数一共就4个:153,370,371,407。

因此我们还可以这样写:

#include<iostream>
using namespace std;
int main()
{
	int m, n, cnt = 0;
	while(scanf("%d%d", &m, &n) != EOF)
	{
		for(int i = m; i <= n; i++)
			if(i == 153 || i == 370 || i == 371 || i == 407)
			{
				if(cnt == 0)
				{
					printf("%d", i);
					cnt++;
				}
				else if(cnt > 0) printf(" %d", i);
			}
		cnt == 0 ? printf("no\n") : printf("\n");
		cnt = 0;
	}
	return 0;
}

没有C语言基础的同学们,可以先学习一下C语言语法,我会整理好,后面发出来
我已经写好了,可以去C语言程序设计专栏第一周的内容

本周其他练习:

C语言程序设计专栏

C/C++编程学习 - 第3周 ① A + B problem

C/C++编程学习 - 第3周 ② 大象喝水

C/C++编程学习 - 第3周 ③ 计算球体积

C/C++编程学习 - 第3周 ④ 水仙花数

C/C++编程学习 - 第3周 ⑤ 计算两点间距离

C/C++编程学习 - 第3周 ⑥ 温度表达转化

C/C++编程学习 - 第3周 ⑦ 数值统计

C/C++编程学习 - 第3周 ⑧ 质数和

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水蛙菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值