#include
#include
int main()
{
int a,b,c,d,i,l;
i=1;
l=1;
a=0;
b=0;
while(a<961)
{
a=i*i;
i=i+1;
printf("%d\n",a);
}
while(b<1000)
{
b=l*l*l;
l=l+1;
printf("%d\n",b);
}
return 0;
}
怎么将输出的结果从小到大排序!!
似乎你还没学数组?
你的代码的话某些数会算两遍,所以最后sort之后我加了unique。
#include <cstdio>
#include <algorithm>
using namespace std;
int f[1000];
int n;
int main()
{
int a,b,c,d,i,l;
i=1;
l=1;
a=0;
b=0;
while(a<961)
{
a=i*i;
i=i+1;
// printf("%d\n",a);
f[n++] = a;
}
while(b<1000)
{
b=l*l*l;
l=l+1;
// printf("%d\n",b);
f[n++] = b;
}
sort(f, f + n);
n = unique(f, f + n) - f;
for (int i = 0; i < n; ++i)
{
printf("%d\n", f[i]);
}
return 0;
}
http://codepad.org/MAZIPUbh
在线编译通过,结果正确。程序绝对没有问题的。
#include <math.h>
#include <iostream.h>
using namespace std;
int main()
{
for (int i = 1; i <= 1000; i++)
{
if (abs(pow(i, 0.5) - (int)(pow(i, 0.5) + 0.000001)) < 0.001 ||
abs(pow(i, 1/3.0) - (int)(pow(i, 1/3.0) + 0.000001)) < 0.001)
cout << i << endl;
}
}
VC++新建一个控制台程序,不要去掉stdafx.h
直接贴在下面,可以编译。
是C++程序,不是C程序。
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 1000; i++)
{
if (fabs(pow(i, 0.5) - (int)(pow(i, 0.5) + 0.000001)) < 0.001 ||
fabs(pow(i, 1/3.0) - (int)(pow(i, 1/3.0) + 0.000001)) < 0.001)
cout << i << endl;
}
}
这是另一个在线平台的编译结果。
1
4
8
9
16
25
27
36
49
64
81
100
121
125
144
169
196
216
225
256
289
324
343
361
400
441
484
512
529
576
625
676
729
784
841
900
961
1000
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
int nStart = 1, nEnd = 1000;
int i, value;
// 完全平方
for( i = sqrt(double(nStart)); (value = i * i) < nEnd; ++i )
{
cout << value << endl;
}
//完全立方
for( i = sqrt(double(nStart)); (value = i * i * i) < nEnd; ++i )
{
cout << value << endl;
}
}
#include
#include
using namespace std;
int main()
{
for (int i = 1; i <= 1000; i++)
{
if (abs(pow(i, 0.5) - (int)(pow(i, 0.5) + 0.000001)) < 0.001 ||
abs(pow(i, 1/3.0) - (int)(pow(i, 1/3.0) + 0.000001)) < 0.001)
cout << i << endl;
}
}
确实不错,代码就几行,但是解决了问题哦
没有人提筛选法吧,鉴于1000比较小,建立一个数组a[1001] = {0};
从1开始到1000,都做平方和立方,得值v小于1000的,设a[v] = 1;
遍历过程中,把a[v] == 1的地方都输出来。
当然,在大于10以后,不需要再做立方了,在大于31之后,直接遍历,不需要计算平方了。
java写的话 好简单的。
import java.util.*;
public class Test{
public static void main(String[] args) {
Set s = new TreeSet();
for(int i=1;i<=31;i++){
s.add(i*i);
}
for(int i=1;i<=10;i++){
s.add(i*i*i);
}
Iterator it = s.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
结果:
1
4
8
9
16
25
27
36
49
64
81
100
121
125
144
169
196
216
225
256
289
324
343
361
400
441
484
512
529
576
625
676
729
784
841
900
961
1000
你在输出结果之前调用排序算法在输出就是了