Golang程序 显示一个数字的因数
在这个教程程序中,我们将学习如何用Go编程语言显示一个给定数字的因数。
一个数字的因数被定义为任何给定的数字的代数表达式,它的余数为零。所有的复合数都会有两个以上的因数,其中也包括1和数字本身。
例如:将3和7相乘,我们得到21。我们说3和7是21的因子。
下面是一个相同的演示
输入
Suppose our input is = 15
输出
The factors of 15 are: 1 3 5 15
语法
For loop syntax:
for initialization; condition; update {
statement(s)
}
例子-1: 显示如何在Golang程序的Main()函数中显示一个数字的因数
下面是这个Go程序代码中使用的步骤。
算法
- 第1步 – 导入软件包fmt
-
第2步 – 启动函数main()
-
第3步 – 声明并初始化变量
-
第4步 – 使用for循环来显示num%i == 0的因素
-
第5步 – 从i=0到i<=num的for循环迭代
-
第6步 – 使用fmt.Println()打印结果。
例子
package main
// fmt package provides the function to print anything
import "fmt"
// start the main() function
func main() {
// Declare and initialize the variables
var num = 15
var i int
fmt.Println("The factors of the number", num, " are = ")
// using for loop the condition is evaluated.
// If the condition is true, the body of the for loop is executed
for i = 1; i <= num; i++ {
if num%i == 0 {
fmt.Println(i)
}
} // Print the result
}
输出
The factors of the number 15 are =
1
3
5
15
代码描述
-
在上面的程序中,我们首先声明包main。
-
我们导入了fmt包,其中包括包fmt的文件。
-
现在启动函数main()。
-
声明并初始化整数变量num和i。
-
使用for循环对条件进行评估。
-
在程序中,”for “循环被迭代,直到i为假。变量i是for循环中的索引变量。在每一步迭代中,都要检查num是否正好被i整除。这是i是num的一个因子的条件。然后,i的值被增加1。
-
最后,我们使用内置函数fmt.Println()打印结果,一个数字的因数就会显示在屏幕上。
例子-2: 显示如何在Golang程序中用两个独立的函数显示一个数字的因数
以下是Go程序代码中使用的步骤。
算法
- 第1步 – 导入软件包fmt。
-
第2步 – 在main()函数之外创建一个函数 factor()。
-
第3步 – 申报变量i。
-
第4步 – 使用带条件的for循环。
-
第5步 – 启动函数main()。
-
第6步 – 调用函数factor()来寻找一个给定数字的因子。
-
第7步 – 使用fmt.Println()打印结果。
例子
package main
// fmt package provides the function to print anything
import "fmt"
// create a function factor() to find the factors of a number
func factor(a int) int {
// declare and initialize the variable
var i int
// using for loop the condition is evaluated
// If the condition is true, the body of the for loop is executed
for i = 1; i <= a; i++ {
if a%i == 0 {
fmt.Println(i)
}
}
return 0
}
// Start the main() function
func main() {
fmt.Println("The factors of the number 6 are")
// calling the function factor() to find factor of a given number
factor(6)
// Print the result
}
输出
The factors of the number are
1
2
3
6
代码的描述
-
在上面的程序中,我们首先声明包main。
-
我们导入了fmt包,其中包括包fmt的文件。
-
我们在main()函数外创建了一个函数factor(),用于查找给定数字的因子。
-
我们声明了整数变量a和i,变量i是for-loop中的索引变量。
-
在使用for循环的程序中,条件被评估。for “循环被迭代,直到i为假。在每一步迭代中,都要检查’a’是否正好被i整除。条件是i是’a’的一个因子。然后,i的值被增加1。
-
接下来我们开始执行函数main()。
-
现在我们调用函数factor()来寻找一个给定数字的因数。
-
使用内置函数fmt.Println()打印结果,并在屏幕上显示一个数字的因子。
总结
在上面的两个例子中,我们已经成功地编译并执行了Golang代码来显示一个数字的因数。
在上述编程代码中,”for “循环被用来重复一个代码块,直到指定的条件得到满足。我们使用一个内置的函数fmt println()函数在输出屏幕上打印结果。在上面的例子中,我们展示了如何在Go编程语言中实现循环语句。
极客教程