当前位置:文档之家› 精确计算一个数的n次方

精确计算一个数的n次方

精确计算一个数的n次方
摘要本文通过数组,采用累加的算法实现了一个数的n次方的精确计算。

关键词科学计数法;精确计算;累加;数组;n次方;数值溢出;计算机应用Accurate Calculation of a Number n Power
ZENG Hong
First People’s Hospital of Zigong City,Sichuan Province,Computer Center,Zigong 643000,China
Abstract This article through the array, and the algorithm are likely a number of the accurate calculation of power n.
Keywords Scientific notation; Accurate calculation, accumulate, array; N power; Numerical overflow; computer application
通常我们的计算机在计算一个数的n次方时,当数值稍大一点,就会用科学计数法输出结果,引起数值不精确,比如:123140=3.86114×10292,如果结果再大些还会显示溢出,1234150。

本文通过数组,采用累加的算法实现了一个数的n次方的精确计算。

累加的实际n次方的原理:
1232=123×123=123个123相加;
1233=123×123×123=(123个123相加)×123。

为了实现精确计算,我们把输入数的每一位数字分别存放到组数中,如:输入数123,则s(3)=1, s(2)=2, s(1)=3
1 源程序(以VFP为例)
clear
set talk off
input ‘请输入一个整数:’ to m
input ‘请输入次方:’ to n
dimension s(1000) &&定义数组s
dimension g(1000) &&定义数组g
store 0 to s,g &&数组s,g清0
b=m
i=1
do while .t.
g(i)=b-10*int(b/10) &&将输入的数每一位放到数组g个
b=int(b/10) &&除10取整,数位向右移一位
i=i+1
if b=0 then
exit
endif
enddo
i=1
do while i9 then &&如果某位大于9,则向上进位
s(j)=s(j)-10 &&本位减10
s(j+1)=s(j+1)+1 &&高位加1
endif
j=j+1
enddo
k=k+1
enddo
j=1 &&数组g=数组s
do while j0
if g(j)>0 then &&前导0不显示
exit
endif
j=j-1
enddo
?’位数:’+str(j)+chr(13)+str(m)+’的’+str(n)+’次方=‘
do while j>0
??alltrim(str(g(j))) &&显示结果
j=j-1
enddo
2 结论
采用数组分散存放计算中间值和结果,实现了每一位的精确运算,也不会产生数值溢出的错误。

以下是本算法运行的结果:
运行结果:
请输入一个整数:123
请输入次方:300
共有位数:627
123的300次方=93655531278116793862032806038770016912212604532463 50484263496499650406861745144178887843752036121697517673883482216 754295470647651981882124721663811804186359960036568469514598447605070 770293356564938423383310062963026752453597564221840348308626869376090 741540463377983427843596272680193731570534656063513331260966947113406 526668674903172919866170419336631927928895258314598386994381819146842 785885183421238134817690976410674799042639315098000214103228346248227 019350283002860230987657333757950048452482242990781182148408645671298 113849873800884585996471070320176705723853719651043280856815534646383 33156409878362539997076738001
参考文献
[1]章立民.FoxPro命令与函数实用详解.学苑出版社,1994.
[2]严蔚敏,吴伟民.数据结构(C语言版)[M].清华大学出版社,1997,4:1S.。

相关主题