输入所有形如aabb的4位完全平方数(即前两位数字相等,后两位数字相等)
第一种,先枚举所有的aabb数,在通过开平方判断是否为完全平方数
#include<stdio.h>
#include<math.h>
int main(){
for(int a = 1;a <= 9;a++){
for(int b = 0;b <= 9;b++){
int n = a * 1100 + b * 11; // 枚举所有形如aabb的数
int m = floor(sqrt(n) + 0.5); // 将aabb数开平方
//浮点型运算可能存在误差,所以我们应该考虑到误差,使用floor函数
//floor(x)返回不超过x的最大整数,如为0.9999返回0而不是1
//因此我们用floor(x + 0.5)使其区间发生改变,尽量减小误差
if(m * m == n){
printf("%d\n", n);
}
}
}
return 0;
}
第二种,枚举平方根,避免开平方的操作
#include<stdio.h>
int main(){
for(int x = 1; ;x++){
int n = x * x; // 直接得到平方数
if(n < 1000) continue; // 当n < 1000时 跳回到for循环,即执行下一次循环
if(n > 9999) break; // 当n > 9999 时跳出循环
//直接得到1000-9999
int a1 = n / 1000; // 得到aabb中的千位为a1
int a2 = n / 100 % 10; // 得到aabb中的千位为a2
int b1 = n % 100 / 10; // 得到aabb中的千位为b1
int b2 = n % 10; // 得到aabb中的千位为b2
if(a1 == a2 && b1 == b2){
printf("%d\n", n); // 得到符合条件的数,并输出
}
}
return 0;
}
用c++写的话也是差不多的只是需要引用<cmath>头文件
第一种,只是需要引用<cmath>头文件,将printf()改为cout就可以了,其实用printf()也没有什么问题,但如果要使用scanf()函数的话可能会报错但也不一定,如果报错下面两种方式可以尝试
- 在代码的最顶行写入 #define _CRT_SECURE_NO_WARNINGS
- 属性 —> C/C++ —> 预处理器,右侧 预处理器定义 右侧添加上:_CRT_SECURE_NO_DEPRECATE
或是用scanf_s()
当然用c++写代码的话还是建议尽量用符合C++标准的形式
#include<iostream>
#include<cmath>
using namespace std;
int main(){
for(int a = 1;a <= 9;a++){
for(int b = 0;b <= 9;b++){
int n = a * 1100 + b * 11;
int m = floor(sqrt(n) + 0.5);
if(m * m == n){
cout << n << endl;
}
}
}
return 0;
}
第二种
#include<iostream>
using namespace std;
int main(){
for(int x = 1; ;x++){
int n = x * x;
if(n < 1000) continue;
if(n > 9999) break;
int a1 = n / 1000;
int a2 = n / 100 % 10;
int b1 = n % 100 / 10;
int b2 = n % 10;
if(a1 == a2 && b1 == b2){
cout << n << endl;
}
}
return 0;
}