我有一个练习告诉我计算平方根,但是我的程序在6秒内返回结果,我怎么能在2秒内返回平方根?
这是我的实现

  1 /* ************************************************************************** */
  2 /*                                                                            */
  3 /*                                                        :::      ::::::::   */
  4 /*   ft_sqrt.c                                          :+:      :+:    :+:   */
  5 /*                                                    +:+ +:+         +:+     */
  6 /*   By: wjean-ma <wjean-ma@student.42.fr>          +#+  +:+       +#+        */
  7 /*                                                +#+#+#+#+#+   +#+           */
  8 /*   Created: 2015/07/13 13:28:12 by wjean-ma          #+#    #+#             */
  9 /*   Updated: 2015/07/14 16:48:21 by wjean-ma         ###   ########.fr       */
 10 /*                                                                            */
 11 /* ************************************************************************** */
 12
 13 int     ft_sqrt(int nb)
 14 {
 15     int i;
 16     int a;
 17
 18     a = 0;
 19     i = 0;
 20     if (nb <= 0)
 21         return (0);
 22     while (i < nb)
 23     {
 24         a = nb - (i * i);
 25         if (a == 0)
 26             return (i);
 27         else if (a < 0)
 28             return (0);
 29         ++i;
 30     }
 31     return (i);
 32 }

最佳答案

牛顿法是一种容易实现的方法,通常速度足够快。见https://mitpress.mit.edu/sicp/chapter1/node9.html
这个想法是你继续平均你当前的猜测和争论/当前的猜测,直到你的猜测足够接近。例如:

#include <stdio.h>
#include <stdlib.h>


double square_root(double num) {
    double result = 1;
    double range = num * 0.001; /* Answer within 1/10 of a percent. */
    while(abs(result*result - num) > range) {
        result = (result + num/result) / 2;
    }
    return result;
}

int main(int argc, char *argv[], char *envp[]) {
    if(argc < 2) {
        fprintf(stderr, "Usage: %s <number>\n", argv[0]);
        return 1;
    }
    printf("%g\n", square_root(atof(argv[1])));
    return 0;
}

关于c - 返回结果少于2秒,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31410687/

10-11 23:12
查看更多