预计阅读时间:5分钟
‘原题
描述
编写程序,按从小到大的顺序寻找同时符合条件1和2的所有3位数,条件为:
1.该数为完全平方数
2.该数至少有2位数字相同
例如,100同时满足上面两个条件。
输入
输入一个数n,n的大小不超过实际满足条件的3位数的个数。
输出
输出为第n个满足条件的3位数(升序)
样例输入
1
样例输出
100
题目分析
这道题就是枚举,水题一个。
思路
用三重循环枚举每一个可能,判断当前三位数后,如果符合条件,就判断是不是第n个,如果是,就输出。
怎么判断m是不是完全平方数呢?这里就要用到一个名叫floor的函数了
在 C 语言中 floor 函数用于对浮点数 float
或者 double
或者 longdouble
向下取整,也是一个比较常用的函数 ,语法如下:
#include <math.h> //需要包含头文件
extern float floorf(float);//参数为flot类型
extern double floor(double);//参数为double类型
extern long double floorl(long double);//参数为long double类型
注意:floor 函数的返回是 double
类型,并非 int
类型;
floor 函数主要用于对浮点数向下取整,示例如下:
#include <bits/stdc++.h>
int main()
{
printf("floor(50.2) = %f \n", floor(50.2));
printf("floor(0.2) = %f \n", floor(0.2));
printf("floor(-50.2) = %f \n", floor(-50.2));
printf("floor(-0.2) = %f \n", floor(-0.2));
printf("floor(100.2) = %f \n", floor(100.2));
system("pause");
return 0;
}
以上内容来自:https://zhuanlan.zhihu.com/p/433250399
参考代码
#include <iostream>
#include <cmath>
using namespace std;
bool judge(int m)//判断m是不是完全平方数
{
double x=sqrt(m);
if(floor(x)==x)
{
return true;
}
return false;
}
int main()
{
int n;
cin>>n;
int count=0;
for(int i=1; i<=9; i++)
{
for(int j=0; j<=9; j++)
{
for(int k=0; k<=9; k++)
{
int flag1=0,flag2=0;
if(i==j||j==k||k==i)//如果任意两个数相同
{
flag1=1;
}
int s=i*100+j*10+k;
if(judge(s))//判断s是不是完全平方数
{
flag2=1;
}
if(flag1==1&&flag2==1)
{
count++;
if(n==count)
{
cout<<s<<endl;
return 0;
}
}
}
}
}
return 0;
}
希望本博客对大家有所帮助!
本文含有隐藏内容,请 开通VIP 后查看