函数参数有例外吗?

时间:2021-01-16 00:20:55

标签: c function arguments

我正在尝试将参数输入到平方根函数中。该函数将接受值 b 乘以 b,但它不接受值 b 乘以 b 减 4。这是为什么呢?我怎样才能解决这个问题?提前致谢。

#include <stdio.h>

//Function to compute square root of a number

float squareRoot (float x)
{
    float guess = 1.0;

    while (( x/ (guess * guess)) != 1)
    {
        guess = (x/ guess + guess) / 2.0;
    }

    return guess;
 }


int main (void)
{
    float b;
    float valueOne;
    float answerOne;
    float squareRoot (float x);


    printf("give me a 'b'\n");
    scanf("%f", &b);

    valueOne = b*b-4;

    answerOne = squareRoot(valueOne);

    printf("%f", answerOne);

    return 0;
 }

1 个答案:

答案 0 :(得分:1)

浮点相等性检查通常是行不通的。而不是使用

( x/ (guess * guess)) != 1

替换为

( x/ (guess * guess)) >1.0000001 || ( x/ (guess * guess)) <=0.99999999

这将在大多数实际情况下为您提供确定的精度。

相关问题