Time Limit: 1 second
Memory Limit: 2 MB
问题描述 求Y=X1/3次方的值。X由键盘输入(x不等于0,在整型范围内)。利用下列迭代公式计算: yn + 1=2/3*yn+x/(3*yn2)(这里的2是平方),初始值y0=x,误差要求小于ε=10-4次方。
Input
输入只有一行,一个整数x
Output
输出只有一行,输出x和y的值,x按照整数输出,不含小数部分,y的值紧跟其后,加":3x="字样,按照实数形式输出。
Sample Input1
8
Sample Output2
8:3X=2.000000011E+00 (冒号后面无空格)
Sample Input2
0
Sample Output2
error!
【题解】
这题用C++根本写不出来。。
用的pascal。就是一个迭代过程。
把前面算出来的值an+1赋给原来参与运算的an.
然后再用新的an来算an+1即可。
精度就是an+1-an的值。让他的绝对值小于1e-4就可以了
记得x==0时判错。
【代码1】pascal
program cheng;
var
x:longint;
y,y0:real;
begin
readln(x);
if x = 0 then
begin
writeln('error!');
halt;
end;
y0:=x;
repeat
y:=y0;
y0:=2/3*y0+x/(3*y0*y0);
until abs(y-y0) < 1e-4;
writeln(x,':3x=',y0);
end.
【代码2】C++版(但是不能过测评)
#include <cstdio>
int t;
double temp,temp2,x;
int main()
{
scanf("%d",&t);
x = t;
temp = x;
temp2 = ((2.0/3.0)*temp) + (x/(3.0*temp*temp));
double tt = temp2-temp;
if (tt < 0) tt=-tt;
while (tt >= 1e-4)
{
temp = temp2;
temp2 = (2.0/3.0)*temp + x/(3.0*temp*temp);
tt = temp2-temp;
if (tt <0 ) tt=-tt;
}
printf("%d:3X=%E",t,temp2);
return 0;
}