我正在编写一个程序,该程序计算5个数字的阶乘并以表格形式输出结果,但是我一直得到 0 。
基本公式:。 n! = n×(n-1)!
我尝试过:
CLS
DIM arr(5) AS INTEGER
FOR x = 1 TO 5
INPUT "Enter Factors: ", n
NEXT x
f = 1
FOR i = 1 TO arr(n)
f = f * i
NEXT i
PRINT
PRINT "The factorial of input numbers are:";
PRINT
FOR x = 1 TO n
PRINT f(x)
NEXT x
END
我期望:
Numbers Factorrials
5 120
3 6
6 720
8 40320
4 24
答案 0 :(得分:1)
您犯了一些错误
FOR i = 1 TO arr(n)
在哪里定义n 您也从未将实际值存储到arr
PRINT f(x)
您从代码中也未定义的数组f中提取
答案 1 :(得分:1)
我眼前没有BASIC解释器,但是我认为这是您想要的:
CLS
DIM arr(5) AS INTEGER
DIM ans(5) AS LONG 'You need a separate array to store results in.
FOR x = 1 TO 5
INPUT "Enter Factors: ", arr(x)
NEXT x
FOR x = 1 to 5
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial of input numbers are:";
PRINT
PRINT "Numbers", "Factorials"
FOR x = 1 TO 5
PRINT STR$(arr(x)), ans(x)
NEXT x
END
不过只是一个注释:在编程中,除非内存不足,否则应避免重用变量。可以做对,但是却为大型程序中的错误发现提供了很多机会。
答案 2 :(得分:1)
可能的解决方案,以计算阶乘的数组:
CLS
DIM arr(5) AS INTEGER
DIM ans(5) AS LONG
FOR x = 1 TO 5
INPUT "Enter Factors: ", arr(x)
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial of input numbers are:";
PRINT
PRINT "Numbers", "Factorials"
FOR x = 1 TO 5
PRINT arr(x), ans(x)
NEXT x
END
答案 3 :(得分:0)
可能的解决方案,用于计算阶乘和平方根的数组:
CLS
PRINT "Number of values";: INPUT n
DIM arr(n) AS INTEGER
DIM ans(n) AS LONG
FOR x = 1 TO n
PRINT "Enter value"; x;: INPUT arr(x)
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial/square root of input numbers are:";
PRINT
PRINT "Number", "Factorial", "Squareroot"
FOR x = 1 TO n
PRINT arr(x), ans(x), SQR(arr(x))
NEXT x
END