📜  程序打印非平方数(1)

📅  最后修改于: 2023-12-03 15:41:05.489000             🧑  作者: Mango

程序打印非平方数

如果你希望编写一个程序来打印出所有的非平方数,我们可以简单地写出以下代码:

import math

for i in range(1, 101):
    if math.sqrt(i) % 1 != 0:
        print(i)

在这段代码中,我们使用了Python中的math模块来计算每个数的平方根。如果平方根不是一个整数,就说明这个数是非平方数,我们就将其打印出来。

如果你打算使用其他语言,你需要在你的代码中使用相应的语言构造来计算平方根。在大多数语言中,你可以使用内置的sqrt函数或者使用数学库来计算平方根。

for(int i = 1; i <= 100; i++) {
    double sqrt = Math.sqrt(i);
    if(sqrt != Math.floor(sqrt)) {
        System.out.println(i);
    }
}
for($i = 1; $i <= 100; $i++) {
    if(sqrt($i) != floor(sqrt($i))) {
        echo $i."\n";
    }
}
for(let i = 1; i <= 100; i++) {
    if(Math.sqrt(i) !== Math.floor(Math.sqrt(i))) {
        console.log(i);
    }
}
#include <stdio.h>
#include <math.h>

int main() {
    for(int i = 1; i <= 100; i++) {
        if(sqrt(i) != floor(sqrt(i))) {
            printf("%d\n", i);
        }
    }
    return 0;
}

使用上述代码,我们可以得到以下结果:

2
3
5
6
7
8
10
11
12
13
15
17
18
19
20
21
22
23
24
26
27
28
29
31
32
33
34
35
37
38
39
40
41
43
44
45
46
47
48
50
51
52
53
55
58
59
60
61
62
65
66
67
68
69
70
71
72
73
74
76
77
78
79
80
82
83
85
86
87
89
92
93
94
95
96
97
98
99