首页 > 试题广场 >

求解立方根

[编程题]求解立方根
  • 热度指数:305844 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
计算一个浮点数的立方根,不使用库函数。
保留一位小数。

数据范围:


输入描述:

待求解参数,为double类型(一个实数)



输出描述:

输出参数的立方根。保留一位小数。

示例1

输入

19.9

输出

2.7
示例2

输入

2.7

输出

1.4
#include<iostream>
#include<iomanip>
using namespace std;
double gCR(double num);
int main()
{
    double num;
    cin>>num;
    cout<<fixed<<setprecision(1)<<gCR(num);
    return 0;
}
double gCR(double num)
{
    double x=0; //定义最终要返回的结果
    double step = 1; //步长
    while(1)
    {
        //如果将要大于输入值,改变步长
        if((x+step)*(x+step)*(x+step)>num)
        {
            step /= 10;
                        //不知道为什么至少要有三位小数才能正确四舍五入到一位
                        //所以这里循环多了一点
            if(step == 0.0001)
            {
                break;
            }
            continue;
        }
        x += step;
    }
    return x;
}
3ms还可以
编辑于 2020-07-16 12:59:41 回复(3)
n = float(input())
if n == 0:
    print('0.0')
elif n>0:
    ans = str(n**(1/3)).split('.')
    if int(ans[1][1])<5:
        print(f'{ans[0]}.{ans[1][0]}')
    else:
        print(f'{ans[0]}.{int(ans[1][0])+1}')
else:
    n *= -1
    ans = str(n**(1/3)).split('.')
    if int(ans[1][1])<5:
        print(f'-{ans[0]}.{ans[1][0]}')
    else:
        print(f'-{ans[0]}.{int(ans[1][0])+1}')

发表于 2022-08-19 15:29:14 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            double num = in.nextDouble();
            double left, right, mid = 0.00;
            left = Math.min(-1.0, num);
            right = Math.max(1.0, num);
            while (right - left > 0.001) {
                mid = (left + right) / 2;
                if (mid * mid * mid > num)
                    right = mid;
                else if (mid * mid * mid < num)
                    left = mid;
                else
                    System.out.printf("%.1f", mid);
            }
            System.out.printf("%.1f", right);
        }
    }
}

发表于 2022-04-06 14:08:45 回复(0)
python3解法
num = float(input())
if num >= 0:
    print("%.1f" % (num ** (1 / 3)))
else:
    print("-%.1f" % abs(num ** (1 / 3)))

发表于 2021-12-12 19:59:03 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
        float num=0;
        String str="";
        while ((str=bf.readLine())!=null){
            num=Float.valueOf(str)*1000000;
            if(num<0){
                num=0-num;
                for(int i=2;i<num;i++){
                    if((i*i*i)>num){
                        float f= 0-(float) (i/100.0);
                        System.out.printf("%.1f",f);
                        System.out.println();
                        break;
                    }
                }
            }else {
                for(int i=2;i<num;i++){
                    if((i*i*i)>num){
                        float f= (float) (i/100.0);
                        System.out.printf("%.1f",f);
                        System.out.println();
                        break;
                    }
                }
            }
        }
    }
}

发表于 2021-09-07 15:50:06 回复(0)
二分法
import java.util.Scanner;

public class Main {
    
    public static void main(String[] args) {
        
        Scanner s = new Scanner(System.in);
        
        while(s.hasNext()){
            double n = s.nextDouble();
            // 特殊值:0,1,-1,直接输出结果
            if(n == 0){
                System.out.println(0);
                continue;
            }
            if(n == 1) {
                System.out.println(1);
                continue;
            }
            if(n == -1) {
                System.out.println(-1);
                continue;
            }
            double l;
            double r;
            // 判断输入值范围,确定左右边界
            if(n < -1) {
                l = n;
                r = -1;
            } else if(n > -1 && n < 0) {
                l = -1;
                r = n;
            } else if(n > 0 && n < 1){
                l = n;
                r = 1;
            } else if(n > 1){
                l = 1;
                r = n;
            } else {
                continue;
            }
            // 递归计算近似值,二分法
            reverse(l, r, n);
            
        } 
        
    }
    
    public static void reverse(double l, double r, double n) {
        double mid = (l + r)/2;
        double tempResult = mid * mid * mid;
        double diff = tempResult - n;
        // 结果保留0.1,则三次方误差为0.001
        if((diff < 0 && diff > -0.001) || (diff > 0 && diff < 0.001)) {
            System.out.println(String.format("%.1f", mid));
            return;
        } else {
            // 重新设置左右边界
            if(tempResult < n){
                l = mid;
            } else {
                r = mid;
            }
            reverse(l, r, n);
        }
    }

}


发表于 2021-03-30 11:22:18 回复(0)
写一个梯度下降的解法。
给定n,求x^3=n的根x。
使用平方误差作为损失函数,损失函数l=(x^3-n)^2
l对x求导数:6*(x**2)*(x**3-n)
因为x小于0时,损失函数不是凸函数,所以特殊处理一下n<0的情况,统一计算n>0的情况。
根据梯度下降很容易写出AC代码。

n=float(input())
op=-1 if n<0 else 1
n=op*n
lr=0.0001
x=0.1
for i in range(1000000):
    delta=6*(x**2)*(x**3-n)
    x=x-lr*delta
print(op*round(x,1))


编辑于 2021-03-14 19:46:04 回复(0)
#include <stdio.h>
#include <math.h>
int main()
{
    double input;
    scanf("%lf",&input);
    double low=0,high=input;
    double mid = (low+high)/2.0;
    while(fabs(input-mid*mid*mid)>0.001)
    {
        if(mid*mid*mid > input)
        {
            high = mid;
        }else
        {
            low = mid;
        }
        mid = (low+high)/2.0;
    }
    printf("%.1f",mid);
    return 0;
}
发表于 2020-07-22 00:20:45 回复(0)
工程代码写多了,变笨了,我首先想的是为了稳定,先把特殊情况的处理逻辑写了,然后在根据需求,划分出四种情况,(-∞,-1),(-1,0),(0,1),(1,+∞),然后先用二分法写1到+∞的情况,然后其他情况就是改一下左右边界与更新中间点的逻辑了。
double getCubeRoot(double input)
{
        if(input == 0)
                return 0;
        if(input == 1)
                return 1;
        if(input == -1)
                return -1;

        if(input > 1)
        {
                return getCubeRootGreaterThan1(input);
        }
        if(input < -1)
        {
                return getCubeRootSmallerThan_1(input);
        }
        if((input > 0) && (input < 1))
        {
                return getCubeRoot01(input);
        }
        if((input > -1) && (input < 0))
        {
                return getCubeRoot_10(input);
        }
}

#define NUMS (0.0001)

double getCubeRootGreaterThan1(double input)
{
        double left,right,middle;
        left = 1;
        right = input;

start:;
          middle = (left + right) / 2;
          double temp = middle * middle * middle;

          temp = temp - input;
          if((temp < NUMS) && (temp > (-NUMS)))
          {
                  return middle;
          }
          if(temp < 0)
          {
                  left = middle;
                  goto start;
          }
          if(temp > 0)
          {
                  right = middle;
                  goto start;
          }
}
发表于 2020-07-20 10:48:44 回复(1)
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            try{
                double dou = scanner.nextDouble();
                System.out.printf("%.1f\n",getCubeRoot(dou,1.0));
                //System.out.printf("%.1f\n",getCubeRoot2(dou,0,dou));
            }catch(Exception e){
                System.out.println("输入类型错误!");
            }
        }
        scanner.close();
    }
    
    //方法一:牛顿迭代法
    //命f(x) = x^3 - a,求解f(x) = x^3 - a = 0。
    //利用泰勒公式展开,即f(x)在xo处的函数值为:
    //f(x) = f(xo) +f'(xo)(x-xo) = xo^3-a+3xo^2(x-x0) = 0,
    //解之得:x = xo - (xo^3 - a) / (3xo^2)。

    public static double getCubeRoot(double target, double Num){
        if(Math.abs(Num*Num*Num-target)>1e-9){
            Num = Num - (Num*Num*Num-target)/(3*Num*Num);
            return getCubeRoot(target,Num);
        }
        return Num;
    }
    
    //方法二:二分查找法
    public static double getCubeRoot2(double target, double min, double max){
        if((max-min)>1e-9){
            double mid = (max+min)/2;
            if(mid*mid*mid>target){
                return getCubeRoot2(target,min,mid);
            }else if(mid*mid*mid<target){
                return getCubeRoot2(target,mid,max);
            }else{
                return mid;
            }
        }else{
           return max;
        }
    }
}
发表于 2020-07-09 10:32:39 回复(0)
#include<iostream>
#include<cmath>
#include<iomanip> 
using namespace std;

int main()
{
    double n;
    while(cin >> n)
        cout << fixed << setprecision(1) << pow(n, 1.0/3) << endl;
	return 0; 
}

编辑于 2020-04-11 09:23:00 回复(0)
while True:
    try:
        a = int(input())
        err = 0.1
        res = a
        temp = 0
        while abs(res-temp) > err:
            temp = res
            res = 2*temp/3+a/3/temp**2
        print("%.1f" %res)
    except:
        break
编辑于 2020-03-07 14:18:03 回复(2)
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextDouble())
        {
            double n = sc.nextDouble();
            double i = 1;
            while(i*i*i < n) i++;
            while(i*i*i > n) i -= 0.1;
            while(i*i*i < n) i += 0.01;
            String res = String.format("%.1f", i);
            System.out.println(res);
        }
        sc.close();
    }
}
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        // 牛顿迭代法
        while(sc.hasNextDouble())
        {
            double y = sc.nextDouble();
            double x;
            for(x = 1.0; Math.abs(x*x*x - y) > 1e-7; x = (2*x + y/x/x)/3);
            String res = String.format("%.1f", x);
            System.out.println(res);
        }
        sc.close();
    }
}


编辑于 2020-02-22 18:34:16 回复(0)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>

using namespace std;

double F(double n, double l, double r){     while(r-l>1e-8)     {         double mid = (l+r)/2;         if(pow(mid,3)<n)             l = mid;         else             r = mid;              }     return l;
}

int main()
{     double n;     while(cin>>n)     {         if(n>=0)             printf("%.1f\n", F(n,0,max(n,1.0)));         else             printf("%.1f\n", F(n,min(n,-1.0),0));     }     return 0;
}

发表于 2018-06-19 01:25:53 回复(0)
#include<cstdio>
#include<iostream>
using namespace std;

//求立方根的迭代
double gen3(double d){
    double x;
    x=1.1;
    for(int i=0;i<100;i++){
        x=x+(d/(x*x)-x)/3.0;
    }
    return x;
}

int  main(){
    double d;
    while(cin>>d){
        double x=gen3(d);
        x+=0.005;
        printf("%.1f\n",x);
    }
    return 0;
}

发表于 2017-09-02 11:23:16 回复(0)
#include<iostream>
#include<cmath>
#include<math.h>
#include<iomanip>
using namespace std;
double cubeX(double x)
{
   double cur=x;
   while(fabs(cur*cur*cur-x)>0.0001)
       cur = cur-(cur*cur*cur-x)/(3*cur*cur);
    return cur;
}
int main(void)
{
    double x;
    cout.precision(2);
    while(cin>>x)
      cout<<cubeX(x)<<endl;
    return 0;          
}

发表于 2017-07-30 17:33:23 回复(0)
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
    double input;
    while(cin>>input)
    {
        double i;
        for(i=0;i*i*i<=input;i+=0.05);
        cout<<setprecision(2)<<i<<endl;
	}
    return 0;
}

发表于 2017-05-01 22:18:36 回复(1)
简单粗暴
#include<stdio.h>
int main(void)
{
    double i;
    double n;
    bool flag;
    while(scanf("%lf",&n) != EOF)
    {     
        flag=0;
        if(n<0)
        {
            n=-n;
            flag=1;
        }
        for(i=0;i*i*i<=n;i=i+0.001);
        if(flag==0)
			printf("%.1f\n",i);
        else
            printf("%.1f\n",-i);
    }
    return 0;
}

发表于 2016-09-03 21:14:26 回复(0)
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			double input = sc.nextDouble();
			System.out.println(getCubeRoot(input));
		}
	}

	public static double getCubeRoot(double input) {
		double x0 = 1;
		double x1 = x0 - (x0 * x0 * x0 - input) / (3 * x0 * x0);
		while (Math.abs(x1 - x0) > 0.000001) {
			x0 = x1;
			x1 = x0 - (x0 * x0 * x0 - input) / (3 * x0 * x0);
		}
		DecimalFormat df = new DecimalFormat("#0.0");
		return Double.parseDouble(df.format(x1));
	}
}

发表于 2016-09-02 15:43:52 回复(0)
import java.text.DecimalFormat;
import java.util.*; 

public class Main { 	
	
	/**
	 * 功能:求解立方根
	 */
	public static double getCubeRoot(double d){
		double j = 0.0001;
		for(double i = 0; i < d; i = i + j){
			if((i*i*i - d > 0 && i*i*i - d < 0.01) || (i*i*i - d < 0 && d - i*i*i < 0.01))
				return i;
		}
		return 0;
	}
	
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			double d = sc.nextDouble();
			DecimalFormat df = new DecimalFormat("0.0");			
			System.out.println(df.format(getCubeRoot(d)));
		}
		sc.close();
    }
}

发表于 2016-08-19 19:03:14 回复(0)